繁体   English   中英

如何解决越界索引错误?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM