java_guy java_guy - 26 days ago 11
Java Question

Word Scramble Not Scrambling Words

This program is supposed to shuffle the letters in the strings input, how ever it is just repeating the input. I am not sure what I am doing wrong, the issue seems to be in the scrambler function. Thank you

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();

while (in.hasNext()) {
String str = in.next();
System.out.println(str);
}
}

//shuffle letters in word besides first and last
public static String scrambler(String str, Random r) {

//basic char array for input strings
char[] a = str.toCharArray();

//scramble letters
for (int i = 0; i < a.length; i++) {
//shuffle letters in word besides first and last
int j = r.nextInt(a.length);

char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return new String(a);
}

Answer Source

You're not calling Scrambler method, you should write

public static void main( String[] args){

  Scanner in = new Scanner(System.in);
  Random r = new Random();
  while(in.hasNext()){
    String str = in.next();
    System.out.println(scrambler(str,r));
  }