Question

In: Computer Science

This lab uses a Student class with the following fields: private final String firstName; private final...

This lab uses a Student class with the following fields:

private final String firstName;
private final String lastName;
private final String major;
private final int zipcode;
private final String studentID;
private final double gpa;

A TestData class has been provided that contains a createStudents() method that returns an array of populated Student objects.

Assignmen

The Main method prints the list of Students sorted by last name. It uses the Arrays.sort() method and an anonymous Comparator object to sort the array by the student’s last name.

Using the Arrays.sort() method and anonymous Comparator objects print out the array of students using the following three sorting criteria:

  1. Sorted in order of major (A-Z)
  2. Sorted by zip code (increasing)
  3. Sorted by Grade Point Average (GPA) (decreasing)

Note: when sorting by GPA, you will need to be clever to correctly sort GPA’s such as 3.1, 3.2, 3.4 in the correct order.

Note: In this assignment the Comparator class will be instantiated as:

                new Comparator<Student>()

The <Student> type argument means that the Comparator operates on Student objects. You will learn more about this in the next lesson on Generics.

Example Output

Students Sorted By LastName

First Name   Last Name    Major              Zip Code     GPA        

Penny        Adiyodi      Finance            90304        3.1        

Marina       Andrieski    Marketing          76821        3.4        

Quentin      Coldwater    Biology            43109        2.7        

Henry        Fogg         Botany             49022        3.8        

Margo        Hanson       Psychology         56231        2.91       

Josh         Hoberman     Astronomy          33021        2.5        

Kady         Orloff-Diaz English            65421        3.2        

Alice        Quinn        Math               89123        4.0        

Eliot        Waugh        Chemistry          12345        2.1        

Julia        Wicker       Computer Science   43210        4.0        

==============================================================

Students Sorted By Major

First Name   Last Name    Major              Zip Code     GPA        

Josh         Hoberman     Astronomy          33021        2.5        

Quentin     Coldwater    Biology            43109        2.7        

Henry        Fogg         Botany             49022        3.8        

Eliot        Waugh        Chemistry          12345        2.1        

Julia        Wicker       Computer Science   43210        4.0        

Kady         Orloff-Diaz English            65421        3.2        

Penny        Adiyodi      Finance            90304        3.1   

==============================================================

Students Sorted By Zip Code

First Name   Last Name    Major              Zip Code     GPA        

Eliot        Waugh        Chemistry          12345        2.1        

Josh         Hoberman     Astronomy          33021        2.5        

Quentin      Coldwater    Biology            43109        2.7        

Julia        Wicker       Computer Science   43210        4.0        

Henry        Fogg         Botany             49022        3.8        

Margo        Hanson       Psychology         56231        2.91       

Kady         Orloff-Diaz English            65421        3.2        

==============================================================

Students Sorted By GPA

First Name   Last Name    Major              Zip Code     GPA        

Julia        Wicker       Computer Science   43210        4.0        

Alice        Quinn        Math               89123        4.0        

Henry        Fogg         Botany             49022        3.8        

Marina       Andrieski    Marketing          76821        3.4        

Kady         Orloff-Diaz English            65421        3.2   

Coding:

package home;

import java.util.Arrays;
import java.util.Comparator;

public class Main {

public static void main(String[] args) {
Student[] students = TestData.createStudents();
Arrays.sort(students,new Comparator<Student>() {
public int compare(Student s1,Student s2) {
String lastname1 = s1.getLastName();
String lastname2 = s2.getLastName();
return lastname1.compareTo(lastname2);
}
});
printStudentList("Students Sorted By LastName",students);

// TODO - sort students by major
printStudentList("Students Sorted By Major",students);

// TODO - sort students by zip code
printStudentList("Students Sorted By Zip Code",students);

// TODO - sort students by GPA
printStudentList("Students Sorted By GPA",students);
}

public static void printStudentList(String title,Student[] list) {
final String format = "%-12s %-12s %-18s %-12s %-12s\n";
System.out.println(title);
System.out.printf(format,"First Name","Last Name","Major","Zip Code","GPA");
for (Student s : list) {
System.out.printf(format,s.getFirstName(),s.getLastName(),s.getMajor(),s.getZipcode(),s.getGpa());
}
System.out.println("==============================================================\n");
}
}

package home;

/**
* Student class (immutable)
*/
public final class Student {
private final String firstName;
private final String lastName;
private final String major;
private final int zipcode;
private final String studentID;
private final double gpa;

public Student(String firstName, String lastName, String major, int zipcode, String studentID, double gpa) {
this.firstName = firstName;
this.lastName = lastName;
this.major = major;
this.zipcode = zipcode;
this.studentID = studentID;
this.gpa = gpa;
}

public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}

public String getMajor() {
return major;
}

public int getZipcode() {
return zipcode;
}

public String getStudentID() {
return studentID;
}

public double getGpa() {
return gpa;
}
}

package home;

public class TestData {
public static Student[] createStudents() {
Student[] students = {
new Student("Julia","Wicker","Computer Science",43210,"A0123",4.0),
new Student("Quentin","Coldwater","Biology",43109,"D3902",2.7),
new Student("Eliot","Waugh","Chemistry",12345,"Z0101",2.1),
new Student("Penny","Adiyodi","Finance",90304,"M2030",3.1),
new Student("Margo","Hanson","Psychology",56231,"L9832",2.91),
new Student("Alice","Quinn","Math",89123,"U8932",4.0),
new Student("Kady","Orloff-Diaz","English",65421,"K3949",3.2),
new Student("Henry","Fogg","Botany",49022,"R9392",3.8),
new Student("Josh","Hoberman","Astronomy",33021,"H3021",2.5),
new Student("Marina","Andrieski","Marketing",76821,"J3491",3.4)
};
return students;
}
}

Solutions

Expert Solution

The comparators have been explained using comments. Please let me know if there is any problem .

Code:

Student.java:

package home;

/**
 * Student class (immutable)
 */
public final class Student
{
    private final String firstName;
    private final String lastName;
    private final String major;
    private final int zipcode;
    private final String studentID;
    private final double gpa;

    public Student(String firstName, String lastName, String major, int zipcode, String studentID, double gpa)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.major = major;
        this.zipcode = zipcode;
        this.studentID = studentID;
        this.gpa = gpa;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public String getMajor()
    {
        return major;
    }

    public int getZipcode()
    {
        return zipcode;
    }

    public String getStudentID()
    {
        return studentID;
    }

    public double getGpa()
    {
        return gpa;
    }
}

TestData.java:

package home;

public class TestData
{
    public static Student[] createStudents()
    {
        Student[] students =
                {
                new Student("Julia","Wicker","Computer Science",43210,"A0123",4.0),
                new Student("Quentin","Coldwater","Biology",43109,"D3902",2.7),
                new Student("Eliot","Waugh","Chemistry",12345,"Z0101",2.1),
                new Student("Penny","Adiyodi","Finance",90304,"M2030",3.1),
                new Student("Margo","Hanson","Psychology",56231,"L9832",2.91),
                new Student("Alice","Quinn","Math",89123,"U8932",4.0),
                new Student("Kady","Orloff-Diaz","English",65421,"K3949",3.2),
                new Student("Henry","Fogg","Botany",49022,"R9392",3.8),
                new Student("Josh","Hoberman","Astronomy",33021,"H3021",2.5),
                new Student("Marina","Andrieski","Marketing",76821,"J3491",3.4)
        };
        return students;
    }
}

Main.java:

package home;

import java.util.Arrays;
import java.util.Comparator;

public class Main
{

    public static void main(String[] args)
    {
        Student[] students = TestData.createStudents();
        Arrays.sort(students,new Comparator<Student>()
        {
            // This compare method returns 0 if lastName1 equals lastName2,
            // returns -1 if lastName1 is less than lastName2
            // returns 1 if lastName1 is greater than lastName2
            public int compare(Student s1,Student s2)
            {
                String lastName1 = s1.getLastName();
                String lastName2 = s2.getLastName();
                return lastName1.compareTo(lastName2);
            }
        });
        printStudentList("Students Sorted By LastName",students);

        Arrays.sort(students,new Comparator<Student>()
        {
            // This compare method returns 0 if major1 equals major2,
            // returns -1 if major1 is less than major2
            // returns 1 if major1 is greater than major2
            public int compare(Student s1,Student s2)
            {
                String major1 = s1.getMajor();
                String major2 = s2.getMajor();
                return major1.compareTo(major2);
            }
        });
        printStudentList("Students Sorted By Major",students);

        Arrays.sort(students,new Comparator<Student>()
        {
            // This compare method returns 0 if both of the zipCode1 equals zipCode2,
            // returns -1 if zipCode1 is less than zipCode2
            // returns 1 if zipCode1 is greater than zipCode2
            public int compare(Student s1,Student s2)
            {
                int zipCode1 = s1.getZipcode();
                int zipCode2 = s2.getZipcode();

                if(zipCode1 < zipCode2)
                {
                    return -1;
                }

                else if(zipCode1 > zipCode2)
                {
                    return 1;
                }

                return 0;
            }
        });
        printStudentList("Students Sorted By Zip Code",students);

        Arrays.sort(students,new Comparator<Student>()
        {
            // This compare method returns 0 if both of the gpa1 equals gpa2,
            // returns -1 if gpa1 is greater than gpa2
            // returns 1 if gpa1 is lesser than gpa2
            // The order is reversed because we need to sort in decreasing order
            public int compare(Student s1,Student s2)
            {
                double gpa1 = s1.getGpa();
                double gpa2 = s2.getGpa();

                if(gpa1 < gpa2)
                {
                    return 1;
                }

                else if(gpa1 > gpa2)
                {
                    return -1;
                }

                return 0;
            }
        });
        printStudentList("Students Sorted By GPA",students);
    }

    public static void printStudentList(String title,Student[] list) {
        final String format = "%-12s %-12s %-18s %-12s %-12s\n";
        System.out.println(title);
        System.out.printf(format,"First Name","Last Name","Major","Zip Code","GPA");
        for (Student s : list) {
            System.out.printf(format,s.getFirstName(),s.getLastName(),s.getMajor(),s.getZipcode(),s.getGpa());
        }
        System.out.println("==============================================================\n");
    }
}

Sample Output:


Related Solutions

java programing Q: Given the following class: public class Student { private String firstName; private String...
java programing Q: Given the following class: public class Student { private String firstName; private String lastName; private int age; private University university; public Student(String firstName, String lastName, int age, University university) { this.firstName = fisrtName; this.lastName = lastName; this.age = age; this.university = university; } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public int getAge(){ return age; } public University getUniversity(){ return university; } public String toString() { return "\nFirst name:" + firstName +...
C++ Classes & Objects Create a class named Student that has three private member: string firstName...
C++ Classes & Objects Create a class named Student that has three private member: string firstName string lastName int studentID Write the required mutator and accessor methods/functions (get/set methods) to display or modify the objects. In the 'main' function do the following (1) Create a student object "student1". (2) Use set methods to assign StudentID: 6337130 firstName: Sandy lastName: Santos (3) Display the students detail using get functions in standard output using cout: Sandy Santos 6337130
Room.java: public class Room { // fields private String roomNumber; private String buildingName; private int capacity;...
Room.java: public class Room { // fields private String roomNumber; private String buildingName; private int capacity; public Room() { this.capacity = 0; } /** * Constructor for objects of class Room * * @param rN the room number * @param bN the building name * @param c the room capacity */ public Room(String rN, String bN, int c) { setRoomNumber(rN); setBuildingName(bN); setCapacity(c); }    /** * Mutator method (setter) for room number. * * @param rN a new room number...
Room.java: public class Room { // fields private String roomNumber; private String buildingName; private int capacity;...
Room.java: public class Room { // fields private String roomNumber; private String buildingName; private int capacity; public Room() { this.capacity = 0; } /** * Constructor for objects of class Room * * @param rN the room number * @param bN the building name * @param c the room capacity */ public Room(String rN, String bN, int c) { setRoomNumber(rN); setBuildingName(bN); setCapacity(c); }    /** * Mutator method (setter) for room number. * * @param rN a new room number...
Java programming. ** Create Account class include: 1/ private long   accountNumber; 2/ private String firstName; 3/...
Java programming. ** Create Account class include: 1/ private long   accountNumber; 2/ private String firstName; 3/ private String lastName; 4/ private double balance; 5/ public Account(long accountNumber, String firstName, String lastName, double balance); 6/ get/set methods for all attributes. 7/ public boolean deposit(double amount);   • deposit only if amount is greater than 10 but   less than 200, add the deposit   amount   to the   currentbalance. • if deposit is   successful return true,   otherwise return false; 8/ public boolean withdrawal(double amount); •...
JAVAFX LAB 2 1. The Soda class has two fields: a String for the name and...
JAVAFX LAB 2 1. The Soda class has two fields: a String for the name and a double for the price. 2. The Soda class has two constructors. The first is a parameterized constructor that takes a String and a double to be assigned to the fields of the class. The second is a copy constructor that takes a Soda object and assigns the name and price of that object to the newly constructed Soda object. 3. The Soda class...
The Instructor class consists of a firstname (String), lastname (String), office building (String) and room number...
The Instructor class consists of a firstname (String), lastname (String), office building (String) and room number (int). There is a no-arg constructor that initializes the properties to “Albert”, “Einstein”, “McNair”, 420. There is also a constructor with a parameter for each class property. Finally, there is a toString() method that returns each property separated by an asterisk * . Create a Netbeans project and name it CourseScheduler. Implement the Instructor class in Java. Declare and instantiate two Instructor objects in...
In Java, Here is a basic Name class. class Name { private String first; private String...
In Java, Here is a basic Name class. class Name { private String first; private String last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Name other) { return this.first.equals(other.first) && this.last.equals(other.last); } } Assume we have a program (in another file) that uses this class. As part of the program, we need to write a method with the following header: public static boolean exists(Name[] names, int numNames, Name name) The goal of...
Programming Language: C# Person Class Fields - password : string Properties + «C# property, setter private»...
Programming Language: C# Person Class Fields - password : string Properties + «C# property, setter private» IsAuthenticated : bool + «C# property, setter absent» SIN : string + «C# property, setter absent» Name : string Methods + «Constructor» Person(name : string, sin : string) + Login(password : string) : void + Logout() : void + ToString() : string Transaction Class Properties + «C# property, setter absent » AccountNumber : string + «C# property, setter absent» Amount : double + «C#...
How do you write the constructor for the three private fields? public class Student implements Named...
How do you write the constructor for the three private fields? public class Student implements Named { private Person asPerson; private String major; private String universityName; @Override public String name() { return asPerson.name(); }
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT