gpt4 book ai didi

java - 为什么我会收到越界错误?

转载 作者:行者123 更新时间:2023-12-02 02:50:47 24 4
gpt4 key购买 nike

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[ ][ ][ ][ ][ ]

Please choose x coordinate for spot 1: 5

Please choose y coordinate for spot 1: 5

异常堆栈跟踪 -

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at chapter.pkg9.and.pkg10.test.Chapter9And10Test.randomNumberGame(Chapter9And10Test.java:117)
at chapter.pkg9.and.pkg10.test.Chapter9And10Test.main(Chapter9And10Test.java:22) C:\Users\Lance\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

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

最佳答案

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

关于java - 为什么我会收到越界错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43862146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com