简体   繁体   中英

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:

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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