有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在学生对象的数组列表中找到ID

public class Student { //student object class containing name and id
    String name;
    int ID;

    public Student(String name, int ID) {
        this.name = name;
        this.ID = ID;
    }
    @Override
    public String toString() {
        return name +" "+ ID;
    }
}
//another class with two array lists, an array of students in a class and an array of students waiting for help
ArrayList<Student> inClass = new ArrayList<Student>();
ArrayList<Integer> inLine = new ArrayList<Integer>(); //IDs of students who are waiting for help

public boolean addStudentInLine(Integer id) { 
   for(int i = 0; i<inClass.size(); i++) {
      if (inClass.get(i).ID != id) {
          return false;
      }
      if (inClass.get(i).ID == id) {
          inClass.add(id);
      }
  }  
}

对于addStudentInLine方法,如果id存在于inClass Arraylist中,我需要将id添加到integer Arraylist inLine中。(只有班级中的学生才能获得帮助)如果该id在inClass arrayList中不存在,请返回false。我不知道如何遍历inClass arrayList以查看id是否已经存在,因为inClass arrayList由学生对象组成。我试过了。contain()方法,但它似乎也不起作用。有人能帮忙吗


共 (1) 个答案

  1. # 1 楼答案

    您应该在addStudentInLine方法中反转条件,如果任何Studentid与ID匹配,则将ID添加到inLine列表并返回true,否则只返回'false'

    public boolean addStudentInLine(Integer id) { 
    
       for(int i = 0; i<inClass.size(); i++) {
    
           if (inClass.get(i).ID.equals(id)) {
               inClass.add(id);
               return true;
            }
    
         }  
        return false;
     }  
    

    也可以使用for-each

     public boolean addStudentInLine(Integer id) { 
    
       for(Student stu : inClass) {
    
           if (stu.ID.equals(id)) {
               inClass.add(id);
               return true;
            }
    
         }  
        return false;
     }