【问题标题】:Working With 2D Arrays in Java [duplicate]在 Java 中使用二维数组 [重复]
【发布时间】: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");



        }



    }
}

【问题讨论】:

标签: java arrays loops logic output


【解决方案1】:
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("}");

【讨论】:

  • 有趣。什么是不正确的?像我在上面的评论中所做的那样,是否很难将列总数与每一列对齐?
  • i = array2d[i].length 产生了 ArrayIndexOutOfBoundsException。如果您在打印语句中包含正确数量的空格,那么格式化输出应该不会太难。
猜你喜欢
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多