是什么导致线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:5

时间:2013-05-25 22:45:43

标签: java

public static void sumrowsandcols(int[][] a) {

    int[] sum = new int[5];
    int i, j, x;
    // Sum of rows
    for (i = 0; i < 5; i++) {
       for (j = 0; j < 5; j++) {
           sum[i] += a[i][j];
       }
    }
    for (x = 0; x < 5; x++) { 
        System.out.println(sum[x]);
    }

    // Sum of columns
    for (i = 0; i < 5; i++) {
       for (j = 0; j < 5; j++) {
           sum[i] += a[j][i];
       }
    }

    for (x = 0; x < 5; x++) { 
        System.out.println(sum[x]);
    }
  }


  public static int[][] generateArray(Scanner myScanner) {

    int numbers[][] = new int[5][5];
    int i, j, x;
    for (i = 0; i < 5; i++)
      System.out.println("Please enter 5 integers for row " + (i+1));     
      for (x = 0; x < 5; x++) {
        j = myScanner.nextInt();
        numbers[i][x] = j;
      } 
      return numbers;
  }

  // Main method. Collection happens, then calls sumrowsandcols. 

  public static void main(String[] args) {   

    int i, j, x;
    Scanner myScanner = new Scanner(System.in);    
    int[][] numbers = generateArray(myScanner);

    // Collect information by row        


    // Print sum of rows and columns
    sumrowsandcols(numbers);    
   }

2 个答案:

答案 0 :(得分:2)

本声明

for (i = 0; i < 5; i++)
   System.out.println("Please enter 5 integers for row " + (i + 1));

在后续for循环之前终止。因此,当语句

时,i已经超出了列数组索引的上限
numbers[i][x] = j;

被调用。结果是ArrayIndexOutOfBoundsException。这就是为什么使用大括号来界定for循环中的范围很重要的原因。同时声明for循环中的变量本身也表明它们在范围内:

for (int i = 0; i < 5; i++) {
   System.out.println("Please enter 5 integers for row " + (i + 1));
      for (int x = 0; x < 5; x++) {
         j = myScanner.nextInt();
         numbers[i][x] = j;
      }
}

答案 1 :(得分:1)

写作时

 for (i = 0; i < 5; i++)
  System.out.println("Please enter 5 integers for row " + (i+1));     '

这一次打印出语句,另一个循环在打印5次后执行。在for循环之后放置括号以将其全部分组。

 public static int[][] generateArray(Scanner myScanner) {

    int numbers[][] = new int[5][5];
    int i, j, x;
    for (i = 0; i < 5; i++){
        System.out.println("Please enter 5 integers for row " + (i + 1));
    for (x = 0; x < 5; x++) {
        j = myScanner.nextInt();
        numbers[i][x] = j;
    }
    }
    return numbers;
}