【发布时间】:2017-06-30 02:24:16
【问题描述】:
已修复:
我删除了我的 while 循环并添加了
if (num.contains(count) == true) {
freq = Collections.frequency(num, count);
for (int k = 0; k < freq; k++) {
sb.append(temp);
}
}
我正在尝试向单词添加随机(0-8 之间)额外的字母副本。示例... do 可能会变成 dddooees 或 doeess。
我的函数有时会工作,但总是会因索引越界错误而崩溃。
我假设我需要在某个时候检查我的 ArrayList 的 NULL 值。我尝试用 if 包裹我的 while 语句来检查它,但没有改进。有什么建议吗?
private static String addLetters(String word) {
StringBuilder sb = new StringBuilder(word.length());
String[] apart = word.split("");
int rand = (int)(Math.random() * 8);
int ran, goUp;
int count = 0;
List<Integer> num = new ArrayList<>();
for (int i = 0; i < rand; i++) {
ran = (int)(Math.random() * word.length());
num.add(ran);
}
Collections.sort(num);
for (int temp : num) {
System.out.println(temp);
}
for (String temp: apart) {
goUp = count;
sb.append(temp);
System.out.printf("String so far: %s\n", sb.toString());
System.out.printf("OUTSIDE: count: %d, goUp: %d\n", count, goUp);
/*
Removed the while loop and added in the above code using collections, works as intended now.
*/
while (count == num.get(goUp)) {
System.out.printf("INSIDE: count: %d, goUp: %d\n", count, num.get(goUp));
sb.append(temp);
System.out.printf("String ADD extra: %s\n", sb.toString());
goUp++;
}
count++;
}
return sb.toString();
}
【问题讨论】:
标签: java arrays list indexoutofboundsexception stringbuilder