0

I am creating a GradeBook program in java and an example output look like:

enter image description here

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

enter image description here

If this is possible please guide me on how to do it

Ele
  • 33,468
  • 7
  • 37
  • 75
Alex G
  • 17
  • 6
  • 2
    Why would that be a 2D array and not a proper data structure which could be sorted easily? – Sami Kuhmonen Jan 17 '18 at 22:09
  • And what do you mean by that? – Alex G Jan 17 '18 at 22:11
  • Use an object containing the data, put them in an array or list and sort. Data types are different anyway and usually there’s no reason to handle this kind of data as a 2D array. If you really need to there are ways to do it also. – Sami Kuhmonen Jan 17 '18 at 22:14
  • I understand what you are saying, but I would just like to sort the names of the Students and not the grades – Alex G Jan 17 '18 at 22:32
  • What I think Sami is suggesting is that instead of using a 2D array, you could use POJO Java classes (data objects) which hold a name, test score, and quiz score as fields. Then you could write a comparator that sorts based on the order of a field. But if you _have_ to use a 2D array, this looks like a duplicate of [this SO post](https://stackoverflow.com/questions/15452429/java-arrays-sort-2d-array) – Kyle Venn Jan 17 '18 at 22:40

1 Answers1

2

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

Ele
  • 33,468
  • 7
  • 37
  • 75