java - 列联表

标签 java

我正在努力寻找解决此问题的 Java 代码。首先,我处于初学者水平,这个问题对我来说很难回答。我知道这使用了二维数组,对吗?但是我在为这个问题编写 Java 代码时遇到问题。

问题是:

Write a Java program that

  1. queries a user for the number of rows and columns of a contingency table,
  2. read the data, row by row and
  3. displays the data in tabular form along with the row totals, column totals and grand total.

For example if the six data of 2x3 table are

1,3,6,7,9, and 8. the program displays these six numbers together with the appropriate totals as

1 3 6   | 10  
7 9 8   | 24  
8 12 14 | 34  

The character '|' is used to separate the data from the row totals

最佳答案

我首先建议您忘掉“数组”,多想想“类”。 Java 是一种面向对象的语言。将你想要的行为封装在一个类中。我们称它为 Tableau

你的类(class)至少需要四种不同的行为才能正确:

  1. 从流或某种阅读器(例如 PrintStreamFileInputStream)将值读入 Tableau
  2. 计算 Tableau 的行和列总和
  3. 将 Tableau 呈现为字符串。
  4. 将 Tableau 写入 OutputStream 或某种类型的 Writer。

计算机科学是将复杂的任务分解成更小、更易于管理的部分。这叫做“分解”。这是学习它的好机会。

所以这是一个开始:

package model;

public class Tableau {
    private int numRows; 
    private int numCols; 
    private int[][] values;

    public Tableau(int numRows, int numCols) {
        if (numRows <= 0) throw new IllegalArgumentException("numRows must be positive");
        if (numCols <= 0) throw new IllegalArgumentException("numCols must be positive");
        this.numRows = numRows; 
        this.numCols = numCols; 
        this.values = new int[numRows+1][numCols+1];
    }

    // You add the rest
    public String toString() { 
        StringBuilder builder = new StringBuilder();

        return builder.toString();
    }
}

关于java - 列联表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10787846/

相关文章:

Java - 我的二进制堆实现有多好?

java - Bluemix 中的流分析服务出错

java - 无法将 jmx 连接到远程主机上 docker 中运行的 java 应用程序

java - 在JAVA中如何检查两个ArrayList中的多个数字

java - Vaadin - 如果我使用 AbsoluteLayout,则不会显示表数据

java - 如何以编程方式确定特定字符集中字符的最大大小(以字节为单位)?

java - 无法获取日期 webelement 的唯一 xpath

java - 如何使用 apache poi 为 3 个单元格设置注释

java - 将 Spring bean 注入(inject) RestEasy

java - InstanceOf 关键字在 Java 小程序中不起作用