【问题标题】:Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 20, Size: 20线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:20,大小:20
【发布时间】:2018-10-29 23:04:31
【问题描述】:

我正在尝试编写 lz78 代码作为学校项目,但我不断收到此错误:

线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引: 20,尺寸:20

代码如下:

public class LZ88 {
    ArrayList input = new ArrayList();
    ArrayList stored = new ArrayList();
    Iterator counter = input.iterator();
    int count=0;
    int lz78(String x)
    {
        int length=x.length();
        for(int i=0;i<x.length();i++)
        {
            input.add(x.charAt(i));
        }
        for(int i=0;i<=input.size(); i++)
        {
            if(stored.contains(input.get(i))==true)
            {
                String str ;
                StringBuilder sb = new StringBuilder();
                sb.append(input.get(i));
                sb.append(input.get(++i));
                str=sb.toString();
                while(stored.contains(str)==true)
                {
                    sb.append(input.get(++i));
                    str=sb.toString();

                }
                stored.add(str);
                System.out.println(stored);
            }
            else
            {
                stored.add(x.charAt(i));
                System.out.println(stored);
            }
        }
        return 0;
    }
    public static void main(String[] args) {
        String x ="abaababaababbbbbbbba";
        LZ88 ob = new LZ88();
        ob.lz78(x);
    }

}

【问题讨论】:

  • 这个错误出现在哪一行?什么是堆栈跟踪?请edit您的答案并添加堆栈跟踪。
  • 像您一样将布尔值与 true 进行比较是没有意义的。无论它的实际价值是什么,无论你是否比较它都是一样的。例如if(stored.contains(input.get(i))==true) 在功能上与 if(stored.contains(input.get(i))) 相同

标签: java


【解决方案1】:

for(int i=0;i&lt;=input.size(); i++) 替换为for(int i=0;i&lt;input.size(); i++)

【讨论】:

  • @Mohamed Mamdoh 如果我的答案符合您的问题,请点击我的答案旁边的空心复选标记接受答案,该复选标记位于 VoteDown 箭头下方,因此复选标记变为绿色。如何接受:meta.stackexchange.com/questions/5234/…
猜你喜欢
  • 2017-01-02
  • 2016-01-12
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
相关资源
最近更新 更多