修正:如何修復出界指數錯誤?
我打消了我的while循環,並添加
if (num.contains(count) == true) {
freq = Collections.frequency(num, count);
for (int k = 0; k < freq; k++) {
sb.append(temp);
}
}
我想添加一個隨機的(以及0-8之間)的信件額外拷貝到一個字。例子......可以變成dddooees或doeess。
我的函數有時會起作用,但總是崩潰,並出現一個出界指數錯誤。
我假設我需要檢查一個NULL值我的ArrayList在某個時間點。我試圖用我的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();
}
是的,我看到了,修復它。 – Yawn