Word Scramble not Scrambling Words

时间:2017-09-22 20:13:36

标签: java string algorithm sorting chars

这个程序应该对字符串输入中的字母进行随机播放,但它只是重复输入。我不确定我做错了什么,问题似乎出现在加扰器功能中。谢谢

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);
}

1 个答案:

答案 0 :(得分:1)

你没有调用Scrambler方法,你应该写

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));
  }