【问题标题】:Why am i getting an out of bounds error? [duplicate]为什么我会出现越界错误? [复制]
【发布时间】:2017-05-09 05:58:19
【问题描述】:
public static void randomNumberGame() {
    Scanner input = new Scanner(System.in);
    Random r = new Random();
    int x; 
    int y; 
    int random;
    int total = 0;
    int[][] board = new int[5][5];

    for (int i = 0; i < 5; i++) {
        System.out.print(" " + (i + 1) + " ");
    }
    System.out.println("");

    for (int i = 0; i < board.length; i++) {
        System.out.print(i + 1);
        for (int j = 0; j < board[0].length; j++) {
            board[i][j] = 0;
            System.out.print("[ ]");
        }
        System.out.println("");
    }

    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[0].length; j++) {
            random = r.nextInt(10) + 1;
            if (board[i][j] == 0) {
                board[i][j] = random;
            }

        }
    }

    for (int i = 0; i < 3; i++) {
        System.out.println("Please choose x coordinate for spot " + (i + 1));
        x = input.nextInt();
        System.out.println("Please choose y coordinate for spot " + (i + 1));
        y = input.nextInt(); 

        total += board[x][y];
            System.out.println(total);            

    }


}

输出如下:

1 2 3 4 5

1[ ][ ][ ][ ][ ]

2[ ][ ][ ][ ][ ]

3[ ][ ][ ][ ][ ]

4[ ][ ][ ][ ][ ]

5[ ][ ][ ][ ][ ]

请选择点 1 的 x 坐标: 5

请选择点 1 的 y 坐标: 5

异常堆栈跟踪 -

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 5
在 chapter.pkg9.and.pkg10.test.Chapter9And10Test.randomNumberGame(Chapter9And10Test.java:117)
在 chapter.pkg9.and.pkg10.test.Chapter9And10Test.main(Chapter9And10Test.java:22) C:\Users\Lance\AppData\Local\NetBeans\Cache\8.2\executor-sn-ps\run.xml:53:Java 返回:1
构建失败(总时间:1 秒)

第 117 行包含此 total += board[x][y];

【问题讨论】:

  • 因为长度为 5 的数组具有从 04 的索引。

标签: java arrays indexoutofboundsexception


【解决方案1】:

因为 5(您为 xy 输入的值)不是有效的 xy 值。数组的有效索引为 0 到 4(含)。 (就像在所有循环设置中一样。)让您的用户输入一个 0-4(含)的值,或者允许他们输入 1-5(含)并从 xy 之前删除一个使用它们。

【讨论】:

  • 所以我必须这样做: System.out.println("请选择点的 x 坐标" + (i + 1)); x = input.nextInt(); System.out.println("请选择点的y坐标" + (i + 1)); y = input.nextInt();
  • total += board[x-1][y-1]; 之类的就可以了。
  • 对不起,我正在尝试修复格式,我不知道如何格式化 cmets 中的代码
  • @Lance 或者让您的用户输入 0-4,或者让他们输入 1-5 并在使用之前从 xy 中减去 1。
  • 您忘记检查 xy 的值是否在您的二维数组中。记住:int[][] board = new int[5][5] 绑定是bound[0-4][0-4]!!
猜你喜欢
  • 2019-08-26
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多