需要使用“if”语句识别以下三个中最年轻/最老的名字:我可以通过运行代码成功列出学生,但需要确定三个中最年轻和最老的。
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());
}
}
答案 0 :(得分:0)
我认为你需要这样的东西:
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());