java - 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);
}
}
解决方案
如果你想从另一个类调用一个方法,你可以例如创建一个你试图从中获取方法的类的对象。例如...
如果您拥有的方法位于 A 类内部,则创建该类的对象。
A classAttribute = new A();
然后调用方法使用....
classAttribite.someMethod();
推荐阅读
- python - pytest 中的 tmpdir 是否仅在我们写入文件时才创建文件?
- java - GridView setOnItemClickListener 更改项目背景颜色,删除所有其他项目的背景颜色
- spring - 将 Spring bean 范围从请求更改为单例的影响
- c# - 使用 aspnet 身份的附加验证
- javascript - 为什么 (4 + 5 + "6") 是 96 而 ("4" + 5 + 6) 在 Javascript 上是 456?
- c - 在 C 中读取具有特定格式的文本文件
- c# - 类型 Microsoft.AspNet.Identity.PasswordHasher 未定义
- c# - 如何使用 EF Core 正确更新表中的列表数据
- apache-spark - 如何在 Kafka 集群上运行 Apache Spark 批处理作业?
- javascript - Vue将axios响应传递给不同的方法