Small Short Code in Java using the Comparable interface, Can someone fix the sma
ID: 3738800 • Letter: S
Question
Small Short Code in Java using the Comparable interface, Can someone fix the small Errors please
import java.util.*;
import java.io.*;
public class Student implements Comparable<Student>{
// member variables
private String name;
private int gradelevel;
private double gpa;
// Constructor
public Student ( String n, int g, double gpa){
this.n=name;
this.g=gradelevel;
this.gpa=gpa;}
//Accessor Functions
public String getName(){return name;}
public int getGrade(){return gradelevel;}
public double getGPA(){return gpa;}
// compareTo function
int compareTo(Student other){
if ( getGrade() > other.GetGrade()){ return 1;}
else if (getGrade() < other.getGrade()){return -1;}
else { return 0;} } }
public class interface {
public static void main (String [] args){
Student s1 = new Student ("Ron", 10, 3.5);
Student s2 = new Student ("Mike", 11, 3.5);
int result = s1.compareTo(s2);
if (result >1){
System.out.println(s2.getName() + " Comes Before " + s1.getName() ); }
else if (result < 1){
System.out.println(s1.getName() + "Comes Before " + s2.getName()); }
else{ System.out.println( s1.getName() + " And " + s2.getName()) + " Are Equal ") ;}
}
}
Explanation / Answer
StudentTest.java
public class StudentTest {
public static void main(String[] args) {
Student s1 = new Student("Ron", 10, 3.5);
Student s2 = new Student("Mike", 11, 3.5);
int result = s1.compareTo(s2);
if (result > 1) {
System.out.println(s2.getName() + " Comes Before " + s1.getName());
}
else if (result < 1) {
System.out.println(s1.getName() + " Comes Before " + s2.getName());
}
else {
System.out.println(s1.getName() + " And " + s2.getName()
+ " Are Equal ");
}
}
}
Student.java
public class Student implements Comparable<Student>{
// member variables
private String name;
private int gradelevel;
private double gpa;
// Constructor
public Student ( String n, int g, double gpa){
this.name=n;
this.gradelevel=g;
this.gpa=gpa;}
//Accessor Functions
public String getName(){return name;}
public int getGrade(){return gradelevel;}
public double getGPA(){return gpa;}
// compareTo function
public int compareTo(Student other){
if ( getGrade() > other.getGrade()){ return 1;}
else if (getGrade() < other.getGrade()){return -1;}
else { return 0;}
}
}
Output:
Ron Comes Before Mike
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.