【发布时间】:2017-04-07 15:58:43
【问题描述】:
我的问题涉及在 ArrayList 的对象中搜索特定变量并返回该变量。我的问题之一是 Student 对象包含多个变量字段。
我正在尝试在对象中定位特定变量,然后从数组列表中返回它。
这是主要的方法:
Student s1 = new Student ("student1", 123, "MIS");
Student s2 = new Student("student2", 231, "Finance");
Student s3 = new Student ("student3", 432, "MIS");
Student s4 = new Student ("student4", 438, "Marketing");
Student s5 = new Student ("student5", 429, "MIS");
Student s6 = new Student ("student6", 215, "Accounting");
Student s7 = new Student ("student7", 287, "MIS");
Student s8 = new Student ("student8", 401, "MIS");
ArrayList<Student> myList = new ArrayList<Student>();
myList.add(s1);
myList.add(s2);
myList.add(s3);
myList.add(s4);
myList.add(s5);
myList.add(s6);
myList.add(s7);
myList.add(s8);
StudentDatabaseImplementation st = new StudentDatabaseImplementation();
st.setTheListOfStudents(myList);
st.printTheListOfStudents(myList);
st.getStudent(429);
System.out.println("The name of the student : "+
st.getStudent(429).getName());
在我创建的 Student 类中我写道:
public class Student{
private String name;
private int CWID, ID;
private String major, maj;
private ArrayList<Student> myList = new ArrayList<Student>()
public Student(String name, int CWID, String major)
{this.name=name;CWID=ID; String Major = maj;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public ArrayList<Student> getAllStudents() {return myList;}
-->public Student getStudent(int CWID){if(myList.contains CWID)
{getName();}}
public void setTheListOfStudents(ArrayList<Student> myList) {
this.myList = myList;}
public String getMajorName() {return majorName;}
public void setMajorName(String majorName) {this.majorName = majorName;}
public int getCWID() {return CWID;}
public void setCWID(int studentId) {this.studentCWID = studentCWID;}
private String majorName;
private int studentCWID;
我还能做些什么来返回用户名吗?
【问题讨论】:
-
您的代码看起来不错。使用当前的 getter 获取学生姓名有什么问题?
-
你的
StudentDatabaseImplementation怎么样? -
@TimBiegeleisen 我希望我可以,但是对于这个作业,getStudent 方法是必需的。但是,myList.contains CWID 不会运行,因为它说找不到变量 CWID。
-
这里出现错误:
if(myList.contains CWID) --> if(myList.contains(CWID))。您还应该实现 equals() 方法。 -
@MuratK。我必须使用一个接口来实现 StudentDatabaseImplementation 类,所以我也只需将主代码复制并粘贴到那里。有错吗?
标签: java arrays object methods interface