【发布时间】:2014-02-17 05:00:18
【问题描述】:
我正在尝试重新发布此问题,但要进行更多说明。鉴于下面的代码,我希望输出每列和每行的总数。行总数应位于该特定行中最后一个元素的右侧,列总数应位于给定列中的最后一个元素下方。请参阅我的程序开头的评论,以了解我希望我的输出是什么。我怎么能这样做呢?我还想打印给定用户输入数组的主对角线。因此,在主对角线下方的代码中,将输出为 {1,3,5}。谢谢!
/*
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");
}
}
}
【问题讨论】:
-
编辑这个问题stackoverflow.com/questions/21820588/summing-up-a-2d-array,而不是发布一个关于同一问题的全新问题。
标签: java arrays loops logic output