Question: Java question: Below are three classes I created where you type a first name, last name, and score. The code sorts by last name. I
Java question:
Below are three classes I created where you type a first name, last name, and score. The code sorts by last name. I am having trouble adding the enhancement below.
Add the ability to sort the list by score. The easiest solution is probably to create a second student class (perhaps called StudentScore) that implements the IComparable interface to sort by score rather than by name.
StudentSortApp
import java.util.*;
public class StudentSortApp { public static void main(String[] args) { System.out.println("Welcome to the Student Scores Application."+" "); //instantiate Scanner Object Scanner sc = new Scanner(System.in); System.out.print("Enter number of students to enter: "); //input stream takes in an integer value int numberofStudents = sc.nextInt(); //array to store student name and score Student[] students = new Student[numberofStudents]; //code which prints array of students name and score int t = 0; for( int i = 1; i <= numberofStudents; i++) { System.out.println(""); String studentLastName = Validator.lastName(sc, "Student " + i + " Last name: "); String studentFirstName = Validator.lastName(sc , "Student " + i + " First name: "); int studentScore= Validator.vScore(sc,"Student " + i + " score : "); students [t] = new Student(studentFirstName, studentLastName , studentScore); // increament the array index t = t + 1; } System.out.println(""); Arrays.sort(students, 0, numberofStudents); for(Student i: students) System.out.println(i.getlastName()+", "+i.getfirstName()+": "+i.getScore()); } }
Student Class
public class Student implements Comparable { private String firstName = ""; private String lastName = ""; private int score = 0; // Student Class constructor public Student(String firstName, String lastName, int score) { this.firstName = firstName; this.lastName = lastName; this.score = score; } @Override public int compareTo(Object nextStudent) { Student student =(Student) nextStudent; if(lastName.equals(student.lastName)) { return firstName.compareToIgnoreCase(student.firstName); } return lastName.compareToIgnoreCase(student.lastName); } // returns first Name public String getfirstName() { return firstName; }
// Returns Last Name public String getlastName() { return lastName; }
// Returns Student Score public int getScore() { return score; }
}
Validator
import java.util.Scanner; public class Validator { public static int vScore(Scanner sc, String prompt) { int studentScore = 0; boolean isValid = false; while (isValid == false) { System.out.print (prompt); studentScore = sc.nextInt(); if (studentScore > 100 || studentScore < 0) { System.out.println("Error! You have to enter a score between 0 and 100"); } else { isValid = true; } } return studentScore; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
