2017-02-11 80 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语句的条件中使用的目的一样。你显然是以两种不同的方式使用它。