java - java中的程序,逐行读取数据并以表格形式显示数据以及行总计、列总计和总计

标签 java arrays design-patterns multidimensional-array

问题:编写一个程序,查询用户代表学生及其分数的行数和列数。 逐行读取数据并以表格形式显示数据以及行总计、列总计和总计。

提示

hint

import java.io.*;
class tabular {
    public static void main(String args[]) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
        System.out.println("Enter the number of rows");
        int row = Integer.parseInt(br.readLine());
        System.out.println("Enter the number of columns");
        int col = Integer.parseInt(br.readLine());

        int A[] [] = new int[10][10];
        System.out.println("Enter the numbers below: ");
        for(int r=0; r<row; r++) {
            for(int c=0; c<col; c++) {
                System.out.print("INPUT ["+ r +"] ["+ c +"] = ");
                A[r][c] = Integer.parseInt(br.readLine());
            }
        }
        System.out.println("\nThe matrix generated is: ");

        //Calculating the sum of rows
        int r;
        int c;
        for(r=0; r<row; r++) {
            int tempRow = 0;
            for(c=0; c<col; c++) {
                tempRow += A[r][c];
            }
            A[r][c] = tempRow;
        }
        //Calculating sum of the column
        for(c=0; c<col; c++) {
             int tempCol= 0;
            for(r=0; r<row; r++) {
                tempCol += A[r][c];
            }
            A[r][c] = tempCol;
        }

        //Display the tabular layout
        for(r=0; r<=row; r++) {
            for(c=0; c<=col; c++) {
                System.out.print( A[r][c] + " ");
            }
            System.out.println();
        }

    }
}

OUTPUT
--------
Enter the number of rows
2
Enter the number of columns
3
Enter the numbers below:
INPUT [0] [0] = 1
INPUT [0] [1] = 2
INPUT [0] [2] = 3
INPUT [1] [0] = 4
INPUT [1] [1] = 5
INPUT [1] [2] = 6

The matrix generated is:
1 2 3 6
4 5 6 15
5 7 9 0

最后显示的是0,而不是列或行相加的结果是21。我哪里出错了?

最佳答案

行的总和被创建为另一列。当您计算列的总和时,您缺少添加的列,因此未显示最终总计。 在 for 循环中使用 c < col+1 而不是 c < col。 应该可以解决问题。

关于java - java中的程序,逐行读取数据并以表格形式显示数据以及行总计、列总计和总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39819819/

相关文章:

c - 将数组作为参数传递给函数

hibernate - Hibernate 中的通用 DAO 模式

java - java中的ip地址是否有效

java - 如何让try-finally中的finally等待线程完成?

JavaCV 从资源创建 Mat (InputStream)

android - 扩展Android Activity 的设计模式?

design-patterns - INTERPRETER 是反模式吗?

java - 使用 INNO setup Installer 安装 JRE 时,现有的 JRE 将被卸载。我不想卸载

javascript - 在字符串数组中查找特定字符串

c++ - 就地旋转二维矩形阵列