为什么这不允许我随机重新排列一个单词(字符串)?

时间:2016-10-02 23:50:12

标签: java string character

我试图接受一个字并随机加扰它。我不确定为什么这不起作用。它说'无法解决方法' setCharAt(int,char)'

我不知道该怎么做。任何帮助都是极好的。谢谢!

import java.util.Random;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        String word = scan.next();

        Random ran = new Random();

        StringBuffer newword = new StringBuffer (word);

        int a = ran.nextInt(newword.length());
        int b = ran.nextInt(newword.length());
        char temp;
        temp = newword.charAt(a);
        word.setCharAt(b, newword.charAt(a));






    }
}

1 个答案:

答案 0 :(得分:0)

随机播放两个字符

修改newword(不是word,这是不可变的 String)。另外,我希望StringBuilderStringBuffer。确保a不是b,如果您要将btemp交换为b,则需要a保存StringBuilder newword = new StringBuilder(word); int a = ran.nextInt(newword.length()); int b = ran.nextInt(newword.length()); while (a == b) { b = ran.nextInt(newword.length()); } char temp = newword.charAt(b); newword.setCharAt(b, newword.charAt(a)); newword.setCharAt(a, temp); 。像,

List<Character>

随机播放所有角色

或者,您可以构建一个List<Character> list = new ArrayList<>(); for (char ch : word.toCharArray()) { list.add(ch); } Collections.shuffle(list, ran); // <-- the default behavior w/o `ran` should suffice, // Collections.shuffle(list); StringBuilder newword = new StringBuilder(); for (Character ch : list) { newword.append(ch); } 随机播放列表。像,

{{1}}