Using the compareTo method with an array to sort students by name and test score
Firstly, delete entirely your Comparable
interface. Use Comparable
from the JDK.
Change your code to this
public static class Student implements Comparable<Student> {
// rest of class omitted
@Override
public int compareTo(Student s) {
if (s.lastName.equals(lastName)) {
return firstName.compareToIgnoreCase(s.firstName);
}
return lastName.compareToIgnoreCase(s.lastName);return
}
}
Note also that there is no "else" after a conditional return
, so I omitted that redundant part of the code
newB
Updated on July 09, 2022Comments
-
newB almost 2 years
I need to use the comparable interfact and a compareTo method to sort a list of students alphabetically and then by test score. I'm struggling at getting this to work in my application.
The list of names needs to be read from a text file. I don't know how many names will be in the text file that my professor uses except that it will be less than 100. I am also supposed to display the average of the grades at the bottom as well as write a message next to any student that is 15 points below average. I have not really gotten to the writing message part as I am currently stuck on getting the names and scores to print and sort.
The text file should look something like this:
Steelman Andrea 95
Murach Joel 98
Lowe Doug 82
Murach Mike 93
This is what I have so far... if someone could give me a little direction I'd appreciate it. Thank you.
package chapt11; import java.io.FileReader; import java.util.Arrays; importjava.util.Scanner; public class CH11AS8App { /** * @param args */ public static void main(String[] args) throws Exception { System.out.println("Welcome to the Student Scores Application."); System.out.println(); Scanner aScanner = new Scanner(new FileReader( "src//chapt11//ch11AS8data.txt")); Student [] studentArray; String lastName; String firstName; int examScore = 0; double average = 0; int nStudent = 100; //array size not set unit run time studentArray = new Student[nStudent]; for (int i=0; i<nStudent; i++) { System.out.println(); while (aScanner.hasNext()) { lastName = aScanner.next(); firstName = aScanner.next(); examScore = aScanner.nextInt(); System.out.println("Student " + nStudent++ + " " + firstName + " " + lastName + " " + +examScore); studentArray[i] = new Student(lastName, firstName, examScore); } double sum = 0.0; sum += examScore; average = sum/nStudent; Arrays.sort(studentArray); System.out.println(); for (Student aStudent: studentArray) { System.out.println(aStudent); if (examScore<= (average-10)) { System.out.println ("Score 10 points under average"); } System.out.println("Student Average:" +average); } } } public interface Comparable { int compareTo(Object o); } class Student implements Comparable { private String firstName; private String lastName; private int examScore; public Student(String firstName, String lastName, int examScore) { this.firstName = firstName; this.examScore = examScore; this.lastName = lastName; } // Get & Set Methods public int getExamScore() { return examScore; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } @Override public int compareTo(Object o) { Student s = (Student) o; if (s.lastName.equals(lastName)) { return firstName.compareToIgnoreCase(s.firstName); } else { return lastName.compareToIgnoreCase(s.lastName); } } public String toString() { return lastName + ", " + firstName + ": " + examScore; } }
}
-
arshajii over 11 yearsAre you having a specific problem?
-
newB over 11 yearsI cant get my code to sort the list... I guess I'm not understanding how to use the array and the compareTo method as the code I've written isn't working.
-
-
newB over 11 yearsby the first recommendation do you mean I should omit?: public interface Comparable { int compareTo(Object o); Thank you for your help.
-
newB over 11 yearsThank you for your help... I will work on fixing these things now.
-
newB over 11 yearsI've been able to fix the first few mistake I've made, however struggling with #4. Would fromIndex be 0 and toIndex be 100?
-
newB over 11 yearsThank you, I made the changes, however am still struggling with getting the list to sort in the console. Any ideas why it wouldn't be working?
-
Pshemo over 11 yearsCount how many students you placed in array. Then invoke
Arrays.sort(studentArray,0,studentCounter)
since parameters of this sorting method are:a
the array to be sorted,fromIndex
the index of the first element (inclusive) to be sorted,toIndex
the index of the last element (exclusive) to be sorted. -
newB over 11 yearsI don't know how many students will be in the text file, my professor would not tell us as he said it should work regardless of how many students are in the text file (basically, he may use several text files with different numbers of students in each to test us). I'm sorry if I sound like a total moron, I'm just so new to all of this and can't seem to grasp arrays. I do think I'm getting closer and appreciate your time and help.
-
Pshemo over 11 years@newB before reading students data from file create some counting variable like
int counter=0
and after placing each student in array increase its value, for example ideone.com/mIhD53. Now I am going to sleep so wont answer your questions for few hours. Good luck with your code. -
Bohemian over 11 years@newB how do you know it hasn't sorted it? what output are you getting? (and confirm what input you are giving it).
-
newB over 11 yearsThis is what I'm getting for output... Welcome to the Student Scores Application. Student 1 Andrea Steelman 95 Student 2 Joel Murach 92 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at chapt11.CH11AS8App.main(CH11AS8App.java:43) I'm doing something wrong in the application but as much as I play around with it I can't figure out what...
-
Bohemian over 11 yearsLose the for loop around the read - it doesn't make any sense. Also, use a
List
, not an array. Nobody uses arrays in the real world. I assume this is an assignment - only bad teachers make you use arrays. -
newB over 11 yearsThank you. Unfortunately it is for an assignment and using an array is part of the specifications.