Need to identify the names of the youngest/ oldest of the following three, using "if" statements: I can successfully list students by running the code, but need to identify just the youngest and oldest of the three.
public class app
{
public static void main(String args[])
{
student st1 = new student();
st1.setFirstName("Fred");
st1.setLastName("Fonz");
st1.setAge(44);
student st2 = new student();
st2.setFirstName("John");
st2.setLastName("Smith");
st2.setAge(20);
student st3 = new student();
st3.setFirstName("Zack");
st3.setLastName("Mills");
st3.setAge(21);
System.out.println("student one info = "+ st1.getFirstName()+ " "+
st1.getLastName()+ " "+ st1.getAge());
System.out.println("student two info = "+ st2.getFirstName()+ " "+
st2.getLastName()+ " "+ st2.getAge());
System.out.println("student three info = "+ st3.getFirstName()+ " "+
st3.getLastName()+ " "+ st3.getAge());
}
}
I think you need something like this :
student[] arr = new student[3];
arr[0] = st1;
arr[1] = st2;
arr[2] = st3;
int min_age = Integer.MAX_VALUE, max_age = Integer.MIN_VALUE, min_age_index = 0, max_age_index= 0;
for(int i =0; i <arr.length ; i++){
int age = arr[i].getAge();
if(min_age>age) {
min_age = age;
min_age_index = i;
}
if(max_age<age) {
max_age = age;
max_age_index = i;
}
}
System.out.println("Youngest Student is : "+arr[min_age_index].getFirstName()+" "+arr[min_age_index].getLastName());
System.out.println("Oldest Student is : "+arr[max_age_index].getFirstName()+" "+arr[max_age_index].getLastName());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.