105k views
5 votes
Create a program that takes a string from the command line and prints every permutation of that string You may assume the string will contain all unique characters. CLARIFICATION: You may print the permutations in any order, as long as you print them all. Useful string methods:

User Joshweir
by
7.0k points

1 Answer

2 votes

Answer:

Step-by-step explanation:

The three Java methods below ask for a string and then use that string to call the permute method which will call the switch method within itself to go through the string for each letter and switch the letters that are needed in order to create all the permutations.

public static void main(String[] args)

{

Scanner in = new Scanner(System.in);

System.out.println("Enter String");

String inputString = in.nextLine();

permute(inputString, 0, inputString.length()-1);

}

private static void permute(String input, int start, int end)

{

if (start == end)

System.out.println(input);

else

{

for (int i = start; i <= end; i++)

{

input = Switch(input,start,i);

permute(input, start+1, end);

input = Switch(input,start,i);

}

}

}

public static String Switch(String a, int x, int y)

{

char temp;

char[] charArray = a.toCharArray();

temp = charArray[x] ;

charArray[x] = charArray[y];

charArray[y] = temp;

return String.valueOf(charArray);

}

User ZECTBynmo
by
7.7k points