我試圖重新發布這個問題,但有更多的解釋。鑑於我的代碼如下,我希望輸出每一列和每一行的總和。行總數應該在該特定行中最後一個元素的右側,列總數應低於給定列中的最後一個元素。請參閱我程序開頭的註釋,以瞭解我希望輸出的內容。我怎麼能這樣做呢?另外我想打印出給定用戶輸入數組的主對角線。所以在下面的代碼中,主對角線將被輸出爲{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");
}
}
}
編輯這個問題http://stackoverflow.com/questions/21820588/summing-up-a-2d-array而不是張貼關於同樣的問題一個全新的問題。 –