java - 如何并排打印两个二维数组?

标签 java arrays swing user-interface

所以用户在不同的字段中输入他/她的名字和姓氏。 (必须是那样)

引用图片:enter image description here

我要做的是在他们的 4 个测试标记旁边显示他们的名字。

所以它看起来像这样

约翰·史密斯 55.0 100.0 23.0 50。 简·史密斯 100.0 50.0 76.0 22.0 等等等等。

我的代码是

public class StudentGradesView extends FrameView {
    final static int students=15;
    final static int numOfTest=4;
    final static int firstNLast=2;

    //Start with the first student in the 2D array
    private int row = 0;


    //DELCARING THE 2D ARRAY
    double[][] marks = new double[students][numOfTest];
    String[][] names = new String[students][firstNLast];

    //1D Arrays
    double testScores[]=new double[4];
    String studentNames[]=new String[2];


    public void addInfo(){
        studentNames[0]= firstNameIn.getText();
        studentNames[1]= lastNameIn.getText();

        testScores[0]=Double.parseDouble(testOneIn.getText());
        testScores[1]=Double.parseDouble(testTwoIn.getText());
        testScores[2]=Double.parseDouble(testThreeIn.getText());
        testScores[3]=Double.parseDouble(testFourIn.getText());

        //Add first and last name to 2d array
        for(int col=0;col <studentNames.length; col++){
            names[row][col]= studentNames[col];
        }

        //Add all four test scores to the current student
        for(int col=0;col < testScores.length; col++){
            marks[row][col]= testScores[col];
        }
        //Advance to the next student
        row++;
    }

    public void displayArray(){
        for(int i=0;i<names.length;i++){
            for(int j=0; j<firstNLast;j++){
                finalOutput.append(names[i][j]+" ");
            }
            finalOutput.append("\n");
        }

        for(int i=0; i<marks.length;i++){
            for(int j=0; j <numOfTest; j++){
                finalOutput.append(marks[i][j]+" ");
            }
            finalOutput.append("\n");
        }
    }
}

当我点击 list/displayArray() 时我最终得到了什么;这是: Shows the names separately from the numbers.

Like this here

所以我一直在研究如何让它们并排打印。还有一种方法可以只打印用户输入的条目数吗?如果一个用户输入了一组信息,只打印一行?

谢谢。

最佳答案

在您的 displayArray 方法中,我将首先通过调用 finalOutput.setText("") 清除 JTextArea ,然后在 for 循环中从 0 到行——到目前为止已添加的学生数。否则,您将遍历整个数组,其中行索引上方的所有空值。

更好——不使用数组而是使用数组列表。

更妙的是:创建一个包含单个学生姓名和成绩的 Student 类,并使用单个 ArrayList<Student> .

更好的是——在 JTable 中显示上面的数据。

关于java - 如何并排打印两个二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23450980/

相关文章:

c - 从上一个索引到当前索引搜索数组

Java - 事件处理和反射(reflect)结果的最佳实践

java - GridBag Constraint 仅通过类的构造函数添加,而不是通过方法添加

java - 关于如何将 @autowire 声明放置在父类/接口(interface)的 protected 变量上的混淆。这是如何 Autowiring 的?

java - Java中广泛使用的哈希算法用于实现哈希表?

c - 数组到c中的参数

java - 在宾果纸牌游戏中实现 Java 图形

java - 使用 JavaFX 中另一个打开的窗口中的对象填充 ListView

java - Jr Java-er 希望将参数传递给 Paint

java - 输入存储在 Arraylist 或 String 数组中? (新程序员)Java