Java

OOP GUIDE / WORK

 

STUDENT CLASS

 

Topics

  • Implementing the Comparable interface
  • Implementing the compareTo method
  • Sorting object arrays with Comparable

 

 

TASK – PART 1 – SETUP

 

No solution required.

 

 

TASK – PART 2 – IMPLEMENTING COMPARABLE

 

Here is my solution:

 

 

public class Student implements Comparable

{

     public String lastName;

     public String firstName;

     public int grade;

     public String school;

    

     public Student()

     {

           String[] lastNames = {"Smith", "Do", "Bardot", "Lu", "Green", "Lowe", "Bacon", "Zoom", "Gravy", "TwoShoes", "Monroe", "Hope", "West", "Lopez", "Gray"};

           lastName = lastNames[(int)(Math.random() * lastNames.length)];

          

           String[] firstNames = {"Jimmy", "June", "Abbott", "Luna", "Harry", "Moon", "Lea", "Kayla", "Aryan", "Grace", "Drake", "Kiana", "Burt", "Amitoj", "Xavier", "Shaun", "Mary"};

           firstName = firstNames[(int)(Math.random() * firstNames.length)];

          

           grade = (int)(Math.random() * 4) + 9;

          

           String[] schools = {"Lockerby", "Confed", "Lasalle", "Lo-Ellen"};

           school = schools[(int)(Math.random() * schools.length)];

     }

    

     public String toString()

     {

           return grade + " " + firstName + " " + lastName + " (" + school + ")";

     }

 

     @Override

     public int compareTo(Object o)

     {

           Student other = (Student)o;

           if (this.grade < other.grade)

                return -1;

           else if (this.grade == other.grade)

           {

                return 0;

           }

           else //this.grade > other.grade

           {

                return 1;

           }

     }

}

 

 

import java.util.Arrays;

 

public class StudentTester

{

     public static void main(String[] args)

     {

           Student[] stews = new Student[20];

          

           //Create students

           for (int i=0; i<stews.length; i++)

           {

                stews[i] = new Student();

           }

          

           //Output students

           for (int i=0; i<stews.length; i++)

           {

                System.out.println(stews[i]);;

           }         

          

           Arrays.sort(stews);

           System.out.println("=====");

          

           //Output students

           for (int i=0; i<stews.length; i++)

           {

                System.out.println(stews[i]);;

           }

     }

}