简体   繁体   English

是否可以对2D数组的第一列进行排序,但在Java中保持对应的值相同

[英]Is it possible to sort the first column of a 2D array but keep the corresponding values the same in java

I am creating a GradeBook program in java and an example output look like: 我正在用Java创建GradeBook程序,示例输出如下所示:

在此处输入图片说明

I was wondering if it is possible to sort the students names while keeping their grades in place for example: 我想知道是否可以在保持学生成绩的同时对学生姓名进行排序:

What I want it to look like 我想要它看起来像什么

在此处输入图片说明

If this is possible please guide me on how to do it 如果可能的话,请指导我如何做

Using Data structure 使用数据结构

This structure will print what you want from the second image. 此结构将从第二张图像中打印出您想要的内容。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Student implements Comparable<Student>{
    private String name;
    private int test;
    private int quiz;

    public Student(String name, int test, int quiz) {
        this.name = name;
        this.test = test;
        this.quiz = quiz;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getTest() {
        return test;
    }

    public void setTest(int test) {
        this.test = test;
    }

    public int getQuiz() {
        return quiz;
    }

    public void setQuiz(int quiz) {
        this.quiz = quiz;
    }

    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.name);
    }
}

public class Stack {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Willian", 90, 80));
        students.add(new Student("Charles", 70, 95));

        Collections.sort(students);

        System.out.println("\t\t   Test \tQuiz");
        for (Student s : students) {
            System.out.println(String.format("%s\t\t%d\t\t%d", s.getName(), s.getTest(), s.getQuiz()));
        }
    }
}

Resources 资源资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM