简体   繁体   English

索引越界异常Java索引:3,大小:3

[英]Index Out Of Bounds Exception Java Index: 3, Size: 3

Hi guys while making a word-puzzle game, I came across a problem in double checking that the vertical and horizontal were both words from my current file that was saved to an arraylist. 嗨,大家好,我在制作单词拼图游戏时,遇到了一个问题,就是仔细检查垂直和水平两个方向都是我当前文件中保存在数组列表中的单词。

 String letterSize = "" + size;
    makeLetterWordList(letterSize);
    boolean finished = false;
    while ( !finished ) {
        finished = true;
        for (int i = 0; i < size; i++) {
            int randomYWord = randomInteger(wordList.size());
            String item = wordList.get(randomYWord);
            puzzleListY.add(item);
        }
        for (int i = 0; i <= puzzleListY.size(); i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j <= puzzleListY.size(); j++) {
                sb.append(puzzleListY.get(j).charAt(j));
            }
            randomXWord = sb.toString();
            if (!wordList.contains(randomXWord)) {
                finished = false;
                break;
            } else {
                puzzleListX.add(randomXWord);
            }

        }
    }

The error Produced was as follows: 产生的错误如下:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)

I am struggling to find the mistake in my code can anyone assist me? 我正在努力寻找代码中的错误,有人可以帮助我吗?

Loop should be only till size - 1 循环应仅到大小-1

for (int i = 0; i <= puzzleListY.size(); i++) { // remove =

For other loop as well, Since you are starting from index 0 and there are n elements loop should be from 0 to n-1 对于其他循环,由于您是从索引0开始并且有n个元素,因此循环应从0到n-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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