Search code examples
javacomparablecompareto

Java compareTo method beginner level


I have an assignment where I need to create a Student class where you store the student's neptun code (String nep_c) and the number of points you have achieved in the exam (int point_num). Prepare a public int getMark () method that returns the ticket obtained to the exam as a function of the score according to the following table:

  • between 100 and 90- > 5;
  • between 90 and 80 -> 4;
  • between 80 and 70 -> 3
  • between 70 and 60 -> 2
  • < 60 -> 1

The class implements the Comparable interface and the compareTo () method sort the students based on the neptun code. Within it, by the number of mark you get. Unfortunately I don't understand comperTo method. Can you help me how can I write the correct code?

public class Student implements Comparable{

private String nep_c;
private int point_num;
private int Mark;

public Student(int point_num, String nep_c) {
    this.point_num = 65;
    this.nep_c= "AAA1BB1";
}

public int getMark(){
    if (point_num <= 100 && point_num > 90)
    Mark = 5;
    else if (point_num <= 90 && point_num > 80)
    Mark = 4;
    else if (point_num <= 80 && point_num > 70)
    Mark = 3;
    else if (point_num <= 70 && point_num > 60)
    Mark = 2;
    else if (point_num <= 60)
    Mark = 1;
    else{
        return 0;
    }
    return Mark;
}

public String getNep_c(){
    return nep_c;
}

public int getPoint_num(){
    return point_num;
}

@Override
public int compareTo (Object o){
    return ???;
}

}


Solution

  • sort the students based on the neptun code

    Two parts. Part one, change

    implements Comparable
    

    to

    implements Comparable<Student>
    

    And then

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

    However, you then say Within it, by the number of mark you get. so perhaps you really want

    @Override
    public int compareTo(Student o) {
        return Integer.compare(getMark(), o.getMark());
    }
    

    If you mean to sort by neptun code, and use mark(s) as a tie-breaker then you could do something like

    int c = this.nep_c.compareTo(o.nep_c);
    if (c != 0) {
        return c;
    }
    return Integer.compare(getMark(), o.getMark());
    

    Or, in Java 8+, using Comparator.comparing like

    return Comparator.comparing(Student::getNep_c)
            .thenComparingInt(Student::getMark).compare(this, o);