2017-02-11 77 views
0

修正:如何修復出界指數錯誤?

我打消了我的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(); 
    } 

回答

1

你的循環是字輸入(大小),你NUM(RAND部分),如果字輸入大小比蘭特規模更加大,你有這樣的錯誤(41行)做了num.get(goUp)

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)); 
+0

是的,我看到了,修復它。 – Yawn

0

通常應通過修復錯誤來處理數組索引越界錯誤。

你的邏輯混淆不清,我不確定你的代碼應該如何工作。但是,我確實看到您的崩潰:

比較num數組的用途,如您填寫它的目的與它在while語句的條件中使用的目的一樣。你顯然是以兩種不同的方式使用它。