首页 > 解决方案 > Java - 从数组(类)中查找特定 ID

问题描述

尝试从类中调用方法时遇到一些问题。下面有我的主要方法

private static boolean findStudentId() {
        System.out.println("Please enter your student ID to search for your profile");
        int searchId = scanner.nextInt();
        //need to be able to find a student's profile from the arraylist by searching their ID
        return false;
    }

我试图从另一个类调用一个方法,但不能这样做。这是我要打电话的另一堂课

public boolean findStudent(int id) {
        for(int i = 0; i< students.size();i++)
        {
            if (students.equals(id)) {
                System.out.println("Found the profile containing information for " + id);
//                System.out.println(id.getFirstName()+id.getFirstName()+id.getLastName()+id.getDob());
                return true;
            } else
                System.out.println("Could not find a profile based on the ID you provided");
        }
        return false;
    }


这是我创建的学生班,它宣布学生

public class Student {
    private int id;
    private String firstName;
    private String lastName;
    private String dob;

    public Student(int id,String firstName, String lastName, String dob) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;
    }

    public int getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getDob() {
        return dob;
    }

    public static Student createStudentID(int id,String firstName, String lastName, String dob)
    {
        return new Student(id,firstName, lastName, dob);
    }
}


标签: javaarraysclassintellij-idea

解决方案


如果你想从另一个类调用一个方法,你可以例如创建一个你试图从中获取方法的类的对象。例如...

如果您拥有的方法位于 A 类内部,则创建该类的对象。

A classAttribute = new A();

然后调用方法使用....

classAttribite.someMethod();

推荐阅读