我试图接受一个字并随机加扰它。我不确定为什么这不起作用。它说'无法解决方法' 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));
}
}
答案 0 :(得分:0)
修改newword
(不是word
,这是不可变的 String
)。另外,我希望StringBuilder
到StringBuffer
。确保a
不是b
,如果您要将b
与temp
交换为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}}