-1
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);    
   }
4

2 回答 2

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;
      }
}
于 2013-05-25T22:53:36.143 回答
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;
}
于 2013-05-25T22:59:22.380 回答