【问题标题】:How to fix out of bounds index error?如何修复越界索引错误?
【发布时间】:2017-06-30 02:24:16
【问题描述】:

已修复:

我删除了我的 while 循环并添加了

 if (num.contains(count) == true) {
                freq = Collections.frequency(num, count);

                for (int k = 0; k < freq; k++) {
                    sb.append(temp);
                }
            }

我正在尝试向单词添加随机(0-8 之间)额外的字母副本。示例... do 可能会变成 dddooees 或 doeess。

我的函数有时会工作,但总是会因索引越界错误而崩溃。

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

【问题讨论】:

    标签: java arrays list indexoutofboundsexception stringbuilder


    【解决方案1】:

    您的循环在字输入(大小)上,如果字输入大小大于 rand 大小,您会执行 num.get(goUp)on num(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));
    

    【讨论】:

    • 是的,我明白了,已修复。
    【解决方案2】:

    数组索引越界错误通常应该通过修复错误来处理。

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

    比较 num 数组的用途,如您如何填充它与它在 while 语句的条件中使用的用途所示。显然,您以两种不同的方式使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 2014-06-06
      • 2015-03-22
      • 2014-10-31
      • 1970-01-01
      相关资源
      最近更新 更多