如何修复getAge()以获取代码中最老的学生的年龄?

时间:2018-05-08 23:16:41

标签: java

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Student {


public Student(String name, int age, String major, String SSN) {

    }


public static void main(String[] args) {

        List<Student> studentList = new ArrayList<>();

        studentList.add(new Student("Alice", 22, "Computer Science", "603-28-5324"));
        studentList.add(new Student("Arthur", 19, "Math","402-23-5463"));
        studentList.add(new Student("Kim", 20, "English","607-34-5463"));
        studentList.add(new Student("Jack", 24, "Science","537-52-6324"));
        studentList.add(new Student("Bob", 27, "Computer Science", "345-23-4354"));
        studentList.add(new Student("Sarah", 21, "Music", "355-67-5352"));
        studentList.add(new Student("Mariah", 19, "Business", "567-45-8774"));
        studentList.add(new Student("Robert", 18, "Art", "732-65-7364"));


        Optional<Student> optional = studentList.stream()
                .max((p1, p2) -> p1.getAge() - p2.getAge());
        if (optional.isPresent()) {
            Student oldest = optional.get();
            System.out.println("The Oldest Student is: " +oldest.getAge() + "(" + oldest.getAge() + ")");

            //getAge() doesn't work. How do I make it so that it will be able to recognize the age in the array and print out the name with the age?

        }
    }
}

1 个答案:

答案 0 :(得分:1)

你应该创建成员变量并在构造函数中分配它们

    public class Student {

        String name;
        int age;
        String major;
        String SSN;

        public Student(String name, int age, String major, String SSN) {
            this.name=name;
            this.age=age;
            this.major=major;
            this.SSN=SSN;
        }
        int getAge(){
            return age;
        }
        String getName()
        {
            return name;
        }

//and so on for all your variables
    }