Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,165,593 members, 7,861,832 topics. Date: Saturday, 15 June 2024 at 08:37 PM

Karrigan's Posts

Nairaland Forum / Karrigan's Profile / Karrigan's Posts

(1) (of 1 pages)

Programming / Help Req Wid Java Code. Doubt In ComparableTest Class. Qstn As Cmnt Below by karrigan: 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)
*/

(1) (of 1 pages)

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 8
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.