I am trying to iterate inside some arrays containing the name, last name, id and the score of some student. I have to sort this array in descending format. I have used comparable function and compare the elements according to their scores. This is my code: `
import java.util.Arrays;
import java.util.Scanner;
import java.util.*;
public class Main {
private static class Student {
String fName; // First Name
String lName; // Last Name
int id; // Student ID
int score; // Score
public Student(String fName, String lName, int id, int score) {
this.fName = fName;
this.lName = lName;
this.id = id;
this.score = score;
}
public int getScore() {
return score;
}
}
// Checking if Alphabetic or not
public static boolean alphabetic(String str) {
char[] charArray = str.toCharArray();
for (char c : charArray) {
if (!Character.isLetter(c))
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println("Enter the number of students");
Scanner input = new Scanner(System.in);
int k = input.nextInt(); // number of students
Student[] students = new Student[k];
for (int i = 0; i < k; ) {
System.out.println("Enter id");
int id = input.nextInt();
System.out.println("Enter first name ");
String fName = input.next();
while (alphabetic(fName)== false){
System.out.println("Wrong! Please enter again ");
}
System.out.println("Enter last name ");
String lName= input.next();
while (alphabetic(lName)==false) {
System.out.println("Wrong! Please enter again ");
}
System.out.println("Enter score ");
int score = input.nextInt();
students[i ] = new Student(fName, lName, id, score);
}
class ByScoreComparator implements Comparator<Student> {
@Override public int compare(Student s1, Student s2) {
return Integer.compare(s1.getScore(), s2.getScore());
}
}
Arrays.sort(students, new ByScoreComparator());
System.out.println(Arrays.toString(students));
`
I know that for changing the hashcode, I have to use toString() method but even though I use this method, I still get the hashcodes instead of the values. Can you please help me?
CodePudding user response:
When you use toString() method for an Object you should redefine it at the Object class.
So, you need to add this part of code at Student Class :
@Override
public String toString(){
return "id: " this.id " " "fName: " this.fName " " "lName: " this.lName " " "score: " this.score;
}
And the result is printed as needed :
[id: 2 fName: Lee lName: Jen score: 600, id: 1 fName: Mo lName: Nee score: 900]