I am having some difficulty getting this to print the entire TreeSet It is an assignment and I have beat myself up over this. Hopefully it is something that someone with more knowledge than me can see. If I hide all but one name (and it can be any one name) the program runs fine, but if I try to use all 20 names it thorws an error which I do not understand.
This is the assignment:
Create a class named Student that includes String data fields for firstName and lastName. Override the toString() method to display each object's content. Include a constructor that requires two String parameters to populate the firstName and lastName data fields. Create a Set of 20 Student objects, each having a unique first and last name. Print your Set using a loop. Save your files as Student.java and ClassRoster.java.
Here is my code for both files and the error report that I get.
class Student {
String firstName, lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() {
return firstName;
}
public String lastName() {
return lastName;
}
}
import java.util.*;
public class StudentRoster {
public static void main(String[] args) {
Set<Student> studentSet = new TreeSet<Student>();
studentSet.add(new Student("NIkhil", "Alone"));
// studentSet.add(new Student("Ujwol", "Bastakoti"));
// studentSet.add(new Student("Sharif", "Berdi"));
// studentSet.add(new Student("Kumar", "Gaurab"));
// studentSet.add(new Student("Jessica", "Haverson"));
// studentSet.add(new Student("Valeria", "Holdcroft"));
// studentSet.add(new Student("Queen", "Iwunwa"));
// studentSet.add(new Student("Coreena", "Kinney"));
// studentSet.add(new Student("Yankuba", "Kolley"));
// studentSet.add(new Student("Cori", "Leonard"));
// studentSet.add(new Student("Anuj", "Malla"));
// studentSet.add(new Student("Ekagnon", "Medegan Fagla"));
// studentSet.add(new Student("Jerry", "Misiewicz"));
// studentSet.add(new Student("Prajesh", "Mulmi"));
// studentSet.add(new Student("Rajib", "Pandey"));
// studentSet.add(new Student("Sajeev", "Prajapati"));
// studentSet.add(new Student("Assima", "Sizing"));
// studentSet.add(new Student("Timothy", "Slater Jr."));
// studentSet.add(new Student("Eric", "Strabala"));
// studentSet.add(new Student("David", "Wise"));
Object[] studentArray = studentSet.toArray();
Student s;
for(Object obj : studentArray) {
s = (Student) obj;
System.out.printf("Student = %s %s \n", s.firstName(), s.lastName());
}
}
}
This is the error code I get when I run the program with all 20 names unhidden.
Exception in thread "main" java.lang.ClassCastException: Student cannot be cast
to java.lang.Comparable
at java.util.TreeMap.put(TreeMap.java:542)
at java.util.TreeSet.add(TreeSet.java:238)
at StudentRoster.main(StudentRoster.java:11)
Press any key to exit
Thank you for any help or suggestions you are willing to give.
dugrogrs