Java: Sort lowest-to-highest

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());
  }
}

Answers


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());

Need Your Help

durandal child router with parameter from parent

durandal durandal-2.0

I am trying to initialize a child router to build sub navigation for the customer section of my application.

WSO2 null response

wso2 wso2esb wso2carbon wso2-am wso2dss

I am trying to use WSO2 StoreAPI in my code for performing validations from WSO2.Here is a snippet