2014-02-17 53 views
-1

我試圖重新發布這個問題,但有更多的解釋。鑑於我的代碼如下,我希望輸出每一列和每一行的總和。行總數應該在該特定行中最後一個元素的右側,列總數應低於給定列中的最後一個元素。請參閱我程序開頭的註釋,以瞭解我希望輸出的內容。我怎麼能這樣做呢?另外我想打印出給定用戶輸入數組的主對角線。所以在下面的代碼中,主對角線將被輸出爲{1,3,5}。謝謝!在Java中使用2D陣列

/* 
        1 2 3 Row 0: 6 
        2 3 4 Row 1: 9 
        3 4 5 Row 2: 12 
      Column 0: 6 
      Column 1: 9 
      Column 2: 12 

*/ 
import java.util.Scanner; 
import java.util.Arrays; 


public class Test2Darray { 

    public static void main(String[] args) { 


     Scanner scan =new Scanner(System.in); //creates scanner object 

     System.out.println("How many rows to fill?"); //prompts user how many numbers they want to store in array 
     int rows = scan.nextInt(); //takes input for response 

     System.out.println("How many columns to fill?"); 
     int columns = scan.nextInt(); 
     int[][] array2d=new int[rows][columns]; //array for the elements 

     for(int row=0;row<rows;row++) 
      for (int column=0; column < columns; column++) 
      { 
      System.out.println("Enter Element #" + row + column + ": "); //Stops at each element for next input 
      array2d[row][column]=scan.nextInt(); //Takes in current input 
      } 

     for(int row = 0; row < rows; row++) 
     { 
      for(int column = 0; column < columns; column++) 
       { 
       System.out.print(array2d[row][column] + " "); 
       } 
      System.out.println(); 
     } 

     System.out.println("\n"); 



     } 



    } 
} 
+0

編輯這個問題http://stackoverflow.com/questions/21820588/summing-up-a-2d-array而不是張貼關於同樣的問題一個全新的問題。 –

回答

0
int[] colSums = new int[array2d.length]; 
int[] mainDiagonal = new int[array2d.length]; 

for (int i = 0; i < array2d[0].length; i++) { 
    int rowSum = 0; 
    for (int j = 0; j < array2d.length; j++) { 
     colSums[j] += array2d[i][j]; 
     rowSum += array2d[i][j]; 
     System.out.print(array2d[i][j] + " "); 
     if (i == j) mainDiagonal[i] = array2d[i][j]; 
    } 
    System.out.println(" Row " + i + ": " + rowSum); 
} 
System.out.println(); 
for (int i = 0; i < colSums.length; i++) 
    System.out.println("Column " + i + ": " + colSums[i]); 
System.out.print("\nMain diagonal: { "); 
for (Integer e : mainDiagonal) System.out.print(e + " "); 
System.out.println("}"); 
+0

沒關係。固定。 –

+0

有趣。什麼是不正確的?如果我在上面的評論中做過,那麼是否很難將列的總數與每列對齊? – user3294617

+0

i = array2d [i] .length產生了一個ArrayIndexOutOfBoundsException。如果只在打印語句中包含適當數量的空格,則格式化輸出應該不會太困難。 –