2012-01-24 49 views
-4

這裏是我的代碼,其中的一點是編寫一個程序,該程序隨機地將1到10個20個數字輸入到5行和4列的2維數組中。程序應該輸出二維數組,每行的總和和每列的總和。我想不通的地方我得到這個異常(這是我的總輸出):我的ArrayOutOfBoundsException的來源是什麼?

Project 3... 
2D Array elements: 6, 6, 7, 10, 4, 4, 0, 9, 0, 1, 3, 10, 1, 10, 10, 9, 10, 5, 8, 2, 
Sum of Rows: 115 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 
    at arrayProject.projectthree(arrayProject.java:96) 
    at arrayProject.main(arrayProject.java:19) 

這裏是我的代碼:

public static void projectthree(){ 
    System.out.println("Project 3..."); 
    /*Write a program that randomly inputs 20 numbers from 1 to 10 into a 2-D array of 5 rows and 4 columns. 
    The program should output the 2-D array, the sum of each row storing numbers in a parallel array and 
    the sum of each column storing numbers in a parallel array*/ 
    int array[][] = new int[5][4]; 
    Random randomizer = new Random(); 
    for (int i = 0; i < array.length; i++){ 
     for (int j = 0; j < array[i].length; j++){ 
      array[i][j] = randomizer.nextInt(11); //Assign random values to each element in the array 
     } 
    } 
    System.out.print("2D Array elements: "); 
    for (int i = 0; i < array.length; i++){ 
     for (int j = 0; j < array[i].length; j++){ 
      System.out.print(" " +array[i][j]+ ","); //Output 2D Array 
     } 
    } 

    int[] sumOfRows = new int[array.length]; 
    int[] sumOfColumns = new int[array[0].length]; 

    int sumR = 0; 
    int sumC = 0; 
    for(int row = 0; row < array.length; row++){ 
     for(int col = 0; col < array[0].length; col++){  //Sum of rows 
     sumR += array[row][col]; 
     } 
    sumOfRows[row] = sumR; 
    } 
    System.out.println(" "); 
    System.out.println("Sum of Rows: " + sumR); 


    for(int col = 0; col < array.length; col++){ 
     for(int row = 0; row < array[0].length; row++){ 
      sumC += array[row][col]; 
      } 
    sumOfColumns[col] = sumC; 
    } 
    System.out.println("Sum of Columns:" + sumC); 

} 
+1

你試過調試它嗎? – BNL

+1

哪條線是'96'線? – paislee

+0

對我來說運行良好。但在最後一個for循環中,你不想array [row] .length而不是array [0] .length? –

回答

4

看這個循環:

for(int col = 0; col < array.length; col++){ 
    for(int row = 0; row < array[0].length; row++){ 
     sumC += array[row][col]; 
     } 

您正在訪問array[row][col],但您應該訪問array[col][row] ...或更改您循環的方式。比較這個循環與所有已經工作的人:

for (int i = 0; i < array.length; i++){ 
    for (int j = 0; j < array[i].length; j++){ 
     System.out.print(" " +array[i][j]+ ","); 
    } 
} 

注意如何在這裏i從0到array.length - 1,並作爲索引表達式array[i][j]第一位。

+0

這是另一個無人值守你upvote! – BNL

0

您應該能夠調試這很容易自己...... 的問題是你最後的嵌套的for循環...

你說sumC += array[row][col];, 但你行變量聲明上的內部循環,你需要切換到

sumC += array[col][row]; 
相關問題