java - 不知道是什么导致了我的 ArrayIndexOutOfBoundsException 错误

标签 java arrays

我编写了一段代码,它不断给我一个 ArrayIndexOutOfBoundsException 错误,但我真的不知道为什么。我认为我已经正确设置了数组的大小,但显然这不是真的。即使我将数组的大小设置为 100,我仍然会收到错误。在代码下方您可以找到数据输入。

import java.util.Scanner;

public class GameOfLife {

public static void main(String []args) {

    Scanner scanner = new Scanner(System.in);

    int length = scanner.nextInt();
    int width = scanner.nextInt();
    int generations = scanner.nextInt();
    Boolean[][] cellsInput = new Boolean[length - 1][width - 1];

    System.out.println();   
    int count = 0;
    int y = 0;
    while (scanner.hasNext()) {
        count++;
        if (count <= length) {
            if (scanner.next().equals(".")){
                cellsInput[y++][count] = false;
            } else if (scanner.next().equals("*")) {
                cellsInput[y++][count] = true;
            }
        }
        else {
            count = 0;
            y++;
            if (scanner.next().equals(".")){
                cellsInput[y++][count] = false;
            } else if (scanner.next().equals("*")) {
                cellsInput[y++][count] = true;
            }   
        }
    }

}

}

输入(例如):

15 15 3
. . . . . . . . . . . . . * .
. . . . . . . . . . . . * . .
. . . . . . . . . . . . * * *
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
* * * * * * * * . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .

最佳答案

例如以下行是错误的:

if (count <= length) {

由于您使用 count 作为索引,因此当 count 等于 length 时,它会超过最大索引 length - 1 - 因此出现 ArrayIndexOutOfBoundsException。应该是:

if (count < length) {

关于java - 不知道是什么导致了我的 ArrayIndexOutOfBoundsException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110933/

相关文章:

arrays - 在 mongoDB 中使用数组索引获取数组元素

C++多维数组容量

c - 可以在数组开始之前向后迭代到一个吗

javascript - 连续删除数组项(游戏障碍)

java - Selector.select(超时) x Selector.selectNow()

java - 如何启用 15 个复选框中的任意 5 个复选框?

java - 当每个元素上的操作产生不同的结果计数/持续时间时,保持初始可迭代排序顺序稳定

java - 改进遗留 Java 小程序的性能和外观

java - 首选项中的 ListView

javascript - javascript "break"会完全停止递归函数还是只是停止该实例?