如何修复越界索引错误?

时间:2017-02-11 21:22:33

标签: java arrays list indexoutofboundsexception stringbuilder

FIXED:

我删除了我的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。

我的函数有时会运行,但总是会因Out of Bounds索引错误而崩溃。

我假设我需要在某个时刻检查我的ArrayList的NULL值。我试着用我的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();
    }

2 个答案:

答案 0 :(得分:1)

你的循环是单词输入(大小),你在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));

答案 1 :(得分:0)

通常应通过修复错误来处理数组索引超出范围的错误。

您的逻辑令人困惑,以至于我不确定您的代码应该如何工作。但是,我确实看到了你的崩溃:

比较num数组的用途,如何填充它以及在while语句的条件下使用它的目的。你显然是以两种不同的方式使用它。