下面的代码用于生成 5 个随机字符串,其中包含 9 个字符空间的 X 和 O。打印字符串时,字符串会不断添加到前一个字符串上并变长。如何让字符串在每次生成时在新行上打印?
public static void main(String[] args) {
StringBuilder b = new StringBuilder();
Random r = new Random();
String subset = "XO";
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 9; j++) {
int index = r.nextInt(subset.length());
char c = subset.charAt(index);
b.append(c);
}
String s = b.toString() ;
System.out.println(s);
}
最佳答案
您需要将 stringBuilder 初始化移到第一个 for 循环内。这样,它将删除已有的字符,而不是仅仅将它们附加到末尾。本质上你的 stringBuilder 永远不会重置为空。
关于java - 当循环继续执行时删除随机生成的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24617176/