java - 逐列添加数字的格式问题 [Java]

标签 java arrays matrix multidimensional-array

我首先想说的是,一切都计算得很准确。我遇到的唯一问题是尝试打印回我输入的二维数组以及如何格式化我为每列获得的总计。

这是 3 合 1 计划的一部分。对于第二部分,我必须在 3x4 二维数组中输入 12 个数字。然后控制台返回我输入的数组以及逐列的总和。

它应该是这样的:

Enter 3 rows and 4 columns:
1 2 3 4
5 6 7 8
9 10 11.2 12.5
You entered:
1.0 2.0 3.0 4.0
5.0 6.0 7.0 8.0
9.0 10.0 11.2 12.5
The sums are:
15.0 18.0 21.2 24.5

这是我到目前为止的代码:

else if(choice == 2) {
            // declare the 3x4 array
            System.out.print("Enter a 3 by 4 matrix row by row: ");
            double[][] myArray = new double[3][4];
            // set up the array as an input
            for (int i = 0; i < 3; i++)
              for (int j = 0; j < 4; j++)
                myArray[i][j] = input.nextDouble();

            feature2(myArray);

        } // end of choice 2 block

private static void feature2(double[][] myArray){


    System.out.println("You entered: ");
    // return the entered array in double form
    for (int i = 0; i < myArray.length; i++) {
          System.out.print(myArray[i] + " ");
        }
    // calculate the sums column by column and display the results
    for(int column = 0; column < myArray[0].length; column++) {
        double total = 0;
        for(int row = 0; row < myArray.length; row++)
            total += myArray[row][column];
        System.out.println("The sums are: " + total);

    }
} // end of feature 2

就代码而言,控制台上显示的内容如下:

Enter a 3 by 4 matrix row by row: 
1 2 3 4
5 6 7 8
9 10 11.2 12.5
You entered: 
[D@3d4eac69 [D@42a57993 [D@75b84c92 The sums are: 15.0
The sums are: 18.0
The sums are: 21.2
The sums are: 24.5

如您所见,它计算正确,但格式不正确。如果我需要格式化方面的帮助,我可以从这里获取。

最佳答案

要遍历二维数组,需要嵌套 for 循环。 myArray[i] 的值只是索引 i 处的数组之一的地址。要访问二维数组中的数组元素,您不仅需要访问数组的索引,还需要访问数组中元素的索引 myArray[row][column]。外部循环应遍历数组中的每一行(数组),内部循环应遍历数组中的每一列(数组元素)。最后,在打印出其中一个数组的元素后,应该为下一个数组的元素打印换行符。它应该是这样的,

System.out.println("You entered: ");
    // return the entered array in double form
for (int i = 0; i < myArray.length; i++) {
    for (int j = 0; i < myArray[i].length; j++){
       System.out.print(myArray[i][j] + " ");
    }
    System.out.println();
}
System.out.println("The sums are: ");
// calculate the sums column by column and display the results
    for(int column = 0; column < myArray[0].length; column++) {
        double total = 0;
        for(int row = 0; row < myArray.length; row++)
            total += myArray[row][column];
        System.out.print(total + " ");

    }

关于java - 逐列添加数字的格式问题 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242309/

相关文章:

java - CDI 可以在注入(inject)时扫描配置的文件夹中的 Bean 吗? (热部署)

java - 仅在用户交互后调用 itemStateChanged()

java - 在 Ehcache 3 XML 配置中同时设置 TTL 和 TTI

sql - Postgresql,从 json 数组中检索特定键的值

arrays - 从文本文件中的每一行提取位置字符

javascript - 在javascript中迭代数组和concat

opengl - U-V-N相机坐标系如何用OpenGL解释?

java - 递归查找矩阵中的路径

c - 一行矩阵分配

java - 带有自己类的 NullPointerException