[英]How to fix out of bounds index error?
固定:
我刪除了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。
我的函數有時可以正常工作,但始終會因“越界”索引錯誤而崩潰。
我假設我需要在某個時候檢查ArrayList的NULL值。 我嘗試用while語句包裝是否要檢查它的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();
}
您的循環是在單詞輸入(大小)上,如果您在num(rand部分)上執行num.get(goUp)
,則如果單詞輸入大小大於rand大小,則會出現此錯誤(第41行):
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at com.sgr.games.Stack.addLetters(Stack.java:41)
at com.sgr.games.Stack.main(Stack.java:10)
L39 System.out.printf("OUTSIDE: count: %d, goUp: %d\n", count, goUp);
L40
L41 while (count == num.get(goUp)) {
L42 System.out.printf("INSIDE: count: %d, goUp: %d\n", count, num.get(goUp));
數組索引超出范圍錯誤通常應通過修復錯誤來處理。
您的邏輯令人困惑,以至於我不確定您的代碼應該如何工作。 但是,我確實看到了您的崩潰:
比較num數組的用途,如您在while語句的條件中將其填充的目的所顯示的方式所示。 您顯然以兩種不同的方式使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.