为什么我出错了?

时间:2017-05-09 05:58:20

标签: java arrays indexoutofboundsexception

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

异常堆栈跟踪 -

  

线程中的异常&#34; main&#34; 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-snippets \ run.xml:53:Java返回:1   
BUILD FAILED(总时间:1秒)

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

的行

1 个答案:

答案 0 :(得分:2)

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