import javax.swing.JOptionPane;
public class Permutations {
public static void main(String[] args) throws Exception {
String str = null;
str = JOptionPane.showInputDialog("Enter a word");
StringBuffer strBuf = new StringBuffer(str);
doPerm(strBuf,str.length());
}
private static void doPerm(StringBuffer str, int index){
String[] anArrayOfStrings;
if(index == 0){
System.out.println(str);
}
else {
doPerm(str, index-1);
int currPos = str.length()-index;
for (int i = currPos+1; i < str.length(); i++) {
swap(str,currPos, i);
doPerm(str, index-1);
swap(str,i, currPos);
}
}
}
private static void swap(StringBuffer str, int pos1, int pos2){
char t1 = str.charAt(pos1);
str.setCharAt(pos1, str.charAt(pos2));
str.setCharAt(pos2, t1);
}
}
Using the code above I permutate a word and print them in console.
Sample Input: bad
Output:
bad
bda
abd
adb
dab
dba
I want to show the output in JOptionPane. I tried to replace this line
System.out.println(str);
With this
JOptionPane.showMessageDialog(null, str);
But the all the output does not load in 1 JOptionPane. Instead it show me a JOptionPane with 'bad' and when I click OK or press Enter a JOptionPane with 'bda' will show and so on until it finish the loop. What I want is to show the 6 output in single JOptionPane.
I also try like array but almost the same output.
private static void doPerm(StringBuffer str, int index){
ArrayList<String> list = new ArrayList<String>();
if(index == 0){
list.add(str.toString());
}
else {
doPerm(str, index-1);
int currPos = str.length()-index;
for (int i = currPos+1; i < str.length(); i++) {
swap(str,currPos, i);
doPerm(str, index-1);
swap(str,i, currPos);
}
}
JOptionPane.showMessageDialog(null, list);
}
I guess you are looking for something like this:
You should proceed as follows:
import javax.swing.JOptionPane;
public class Permutation {
public static void main(String[] args) throws Exception {
String str = null;
str = JOptionPane.showInputDialog("Enter a word");
StringBuffer strBuf = new StringBuffer(str);
doPerm(strBuf,str.length());
JOptionPane.showMessageDialog(null,sbuf.toString());
}
static StringBuffer sbuf = new StringBuffer();
private static void doPerm(StringBuffer str, int index){
String[] anArrayOfStrings;
if(index == 0){
//System.out.println(str);
sbuf.append(str+"\n");
}
else {
doPerm(str, index-1);
int currPos = str.length()-index;
for (int i = currPos+1; i < str.length(); i++) {
swap(str,currPos, i);
doPerm(str, index-1);
swap(str,i, currPos);
}
}
}
private static void swap(StringBuffer str, int pos1, int pos2){
char t1 = str.charAt(pos1);
str.setCharAt(pos1, str.charAt(pos2));
str.setCharAt(pos2, t1);
}
}