Help Req Wid Java Code. Doubt In ComparableTest Class. Qstn As Cmnt Below - Programming - Nairaland
Nairaland Forum › Science/Technology › Programming › Help Req Wid Java Code. Doubt In ComparableTest Class. Qstn As Cmnt Below (977 Views)
1 Reply
| Help Req Wid Java Code. Doubt In ComparableTest Class. Qstn As Cmnt Below by karrigan(op): 10:16am On Jan 10, 2013 |
public class Student implements Comparable{ String firstName, lastName; int studentID=0; double GPA=0.0; public Student(String firstName, String lastName, int studentID, double GPA){ if(firstName==null || lastName==null || studentID==0 || GPA ==0.0){ throw new IllegalArgumentException(); } this.firstName=firstName; this.lastName=lastName; this.studentID=studentID; this.GPA=GPA; } public String firstName(){ return firstName; } public String lastName(){ return lastName; } public int studentID(){ return studentID; } public double GPA(){ return GPA; } public int compareTo(Object o){ double f=GPA-((Student)o).GPA; if(f==0){ return 0; } else if(f<0.0){ return -1; } else{ return 1; } } } import collections.Student; import java.util.*; public class ComparableTest { public static void main(String ar[]){ TreeSet studentSet=new TreeSet(); studentSet.add(new Student("Mike", "Larry", 101, 4.0 )); studentSet.add(new Student("William", "Costigan", 102, 2.8 )); studentSet.add(new Student("Jamie", "Sullivan", 103, 3.6 )); studentSet.add(new Student("Dan", "Costello", 104, 2.3 )); Object[] studentArray=studentSet.toArray(); //why is object class used here and what does toArray() method do? Student s; for(Object obj: studentArray){ s=(Student)obj; System.out.printf("Name = %s %s ID = %d GPA = %.1f\n", s.firstName(), s.lastName(), s.studentID(), s.GPA()); } } } /*Output Name = Dan Costello ID = 104 GPA = 2.3 Name = William Costigan ID = 102 GPA = 2.8 Name = Jamie Sullivan ID = 103 GPA = 3.6 Name = Mike Larry ID = 101 GPA = 4.0 BUILD SUCCESSFUL (total time: 0 seconds) */ |
I Doubt If You All Know The Name Of Some Of The Keys On An English Keyboard! • Please Help With Java Code For This Simple App.. • Improve The Speed Of This Java Code. • 2 • 3 • 4
Who Is The Best Programmer On Nairaland • Web Development And App Development Promo ! • Arduino Board For Sale