在Java中使用2D数组

时间:2014-02-17 05:00:19

标签: java arrays loops logic output

我正试图重新发布这个问题,但需要进一步澄清。鉴于我的代码如下,我希望输出每列和每行的总和。行总计应位于该特定行中最后一个元素的右侧,而列总数应低于给定列中的最后一个元素。请查看程序开头的注释,以了解我希望输出的内容。我怎么能这样做?另外,我想打印出给定用户输入数组的主对角线。所以在下面的代码中,主对角线将输出为{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");



        }



    }
}

1 个答案:

答案 0 :(得分: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("}");