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);
}
}
The output is as follows:
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 Stack Trace -
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)
Line 117 is the one containing this total += board[x][y];