简体   繁体   English

如何通过StudentID从arrayList中删除项目?

[英]How can I remove items from arrayList by StudentID?

I need to write a method that removes students from the ArrayList (myRoster) by student ID. 我需要编写一种通过学生ID从ArrayList(myRoster)中删除学生的方法。 If the student ID doesn't exist, the method should print an error message indicating that it is not found. 如果学生证不存在,则该方法应打印一条错误消息,指出找不到该学生证。 I have written a remove method where I'm able to remove item by index. 我写了一个remove方法,可以按索引删除项目。 The error message 'Student with ID 3 was not found' is returning 6 times (3 from first remove and 3 from second error message). 错误消息“未找到ID为3的学生”返回6次(第一次删除3次,第二次错误3次)。 But I want to get one error message for second remove method which I'm calling in main method. 但是我想在主方法中调用第二个remove方法时收到一条错误消息。 A little help would be much appreciated. 一点帮助将不胜感激。

Student Class 学生班

 public class Student {
    private int StudentID;
    private String FirstName;
    private String LastName;
    private String Email;
    private int age;
    private int[] Grades;

    //Constructor
    public Student(int S_ID,String fName,String lName,String email,int Age, 
    int[] grade){
        setStudentID(S_ID);
        setFirstName(fName);
        setLastName(lName);
        setEmail(email);
        setAge(Age);
        setGrade(grade);
    }
    //Accessor Methods (get methods) 
    public int getStudentID(){
        return StudentID;
    }
    public String getFirstName(){
        return FirstName;
    }
    public String getLastName(){
        return LastName;
    }
    public String getEmail(){
        return Email;
    }

    public int getAge(){
        return age;
    }
    public int[] getGrades(){
        return Grades;
    }

    //Mutator methods (set methods)

    public void setStudentID(int StudentID){
        this.StudentID=StudentID;
    }
    public void setFirstName(String FirstName){
        this.FirstName=FirstName;
    }

    public void setLastName(String LastName){
        this.LastName=LastName;
    }
    public void setEmail(String Email){
        this.Email=Email;
    }
    public void setAge(int age){
        this.age=age;
    }
    public void setGrade(int Grade[]){
        this.Grades=Grade; 
    }

}

Roster Class 名册类

 import java.util.ArrayList;


    public class Roster {
    private static ArrayList<Student> myRoster= new ArrayList<>();
    public static void main(String[] args) {
        add(1,"John", "Smith", "John1989@gmail.com", 20, 88,79, 59);
        add(2,"Suzan", "Erickson", "Erickson_1990@gmailcom",19,91,72,85);
        add(3,"Jack","Napoli","The_lawyer99yahoo.com",19,85,84,87);
        add(4,"Erin", "Black","Erin.black@comcast.net",22,91,98,82 );
        add(5,"Henry","Adam","adam1@gmail.com",25,85,84,79);


        remove(3);

        remove(3);//expected: This should print a message saying such a student with this ID was not found

    }

    public static void add(int S_ID,String fName,String lName,String email,int 
    Age, int grade1, int grade2, int grade3){
        int[] Grades={grade1, grade2,grade3};
        Student newStudent= new Student(S_ID, fName, lName, email, Age, Grades);
        myRoster.add(newStudent);
    }



    public static void remove(int StudentID){
          for (int i = 0; i < myRoster.size(); i++){
              if(i == StudentID){
                 myRoster.remove(i);
              }else{
        System.out.println("Student with ID "+StudentID+" was not found");
              }
          }
    }


    }

}
  1. You should never attempt to remove an element from a list while iterating over it. 在迭代列表时, 切勿尝试从列表中删除元素。
  2. Your comparison is incorrect, reason being that you're comparing the for loop control variable i with the parameter StudentID rather it should be if(myRoster.get(i).getStudentID == StudentID) . 您的比较不正确,原因是您正在将for循环控制变量i与参数StudentID比较,而应该是if(myRoster.get(i).getStudentID == StudentID)

The reasoning as to why the text "Student with ID "+StudentID+" was not found" is being printed to the console multiple times is because you've inserted it inside the loop, meaning each time the parameter StudentID doesn't match the value that it's being compared to, it will print the same message... 为什么多次将文本“未找到ID为“ + StudentID +”的学生”的文本打印到控制台的原因是,您已将其插入循环中,这意味着每次参数StudentID不匹配该值时与之比较时,它将打印相同的消息...


To accomplish your task you can simply use the ArrayList#removeIf method to remove the Student with the specified StudentID , else if the ArrayList#removeIf returns false then you can print the appropriate message as shown within the solution below. 要完成任务,您可以简单地使用ArrayList#removeIf方法删除具有指定StudentIDStudent ,否则,如果ArrayList#removeIf返回false,则可以打印相应的消息,如下面的解决方案所示。

public static void remove(int StudentID) {
       if (!myRoster.removeIf(s -> s.getStudentId() == StudentID)) 
           System.out.println("Student with ID " + StudentID + " was not found");    
}

You problem seems to be that your loop in the remove() method isn't looping over studentIDs but just the looping index. 您的问题似乎是您在remove()方法中的循环不是在学生ID上循环,而是在循环索引上。 You should loop over studentIDs. 您应该遍历studentID。 Your code prints each time an ID doesn't match the given ID. 每当ID与给定的ID不匹配时,您的代码就会打印出来。 That's why you get multiple print messages. 这就是为什么您会收到多条打印消息的原因。 You should instead only print if no one matches (ie roster size doesn't change). 您应该只在没有人匹配时打印(即名册大小不变)。

public static void remove(int StudentID){       
   int initialSize = myRoster.size(); //store initial size of roster to check if it changes

   for (int i=0;i<myRoster.size();i++){          

      if(myRoster.get(i).getStudentID == StudentID){
         myRoster.remove(i);
      }

   } 
   //checks if a student was removed which means the ID was found.
   if(initialSize == myRoster.size()){      
       System.out.println("Student with ID "+StudentID+" was not found");       
   }     

}

You can use Iterator interface as well for your purpose as shown below. 您也可以将Iterator界面用于您的目的,如下所示。

public static void remove(int StudentID) {
    Iterator<Student> it = myRoster.iterator();
    while(it.hasNext()) {
        Student stud = (Student)it.next();
        if (stud.getStudentID() == StudentID) {
            it.remove();
            return;
        }       
    }
    System.out.println("Student with ID " + StudentID + " was not found");
}

Your remove method is currently giving the error message once for every student in the list that doesn't have the desired student ID. 您的remove方法当前为列表中每个没有所需学生ID的学生给出一次错误消息。

for (int i=0;i<myRoster.size();i++){
if(i==StudentID){
    myRoster.remove(i);
}else{
System.out.println("Student with ID "+StudentID+" was not found"); }

That print statement is called any time the student at index i does not have the desired ID, not when there are no students that have that ID. 每当索引i的学生没有所需的ID时,即在没有学生具有该ID的情况下,都将调用该打印语句。 An easy way to fix this would be to put a boolean at the start of the method and set it to false. 解决此问题的一种简单方法是在方法的开头放置一个boolean并将其设置为false。 Then, in the if (i == StudentID) block, remove the student and set the value to true. 然后,在if (i == StudentID)块中,删除学生并将其值设置为true。 Then, after the loop is complete, check if the boolean is true; 然后,在循环完成之后,检查布尔值是否为true;否则为false。 if it is true, then the desired student has been removed. 如果是真的,则所需的学生已被删除。 If it is still false, then there is no student with the desired ID. 如果仍然为假,则没有学生具有所需的ID。

It should look something like this: 它看起来应该像这样:

public static void remove(int studentID) {
    boolean studentFound = false;
    for (int i=0;i<myRoster.size();i++){
        if(i==StudentID){
        myRoster.remove(i);
        i--; // you have to decrement this value to account for the missing item
        studentFound = true; // student with desired ID is removed
    }
    if (!studentFound) System.out.println("Student with ID "+StudentID+" was not found");
}

Yes you can do this ,please some add things in your Student class 是的,您可以这样做,请在学生班上添加一些内容

public class Student {
private int StudentID;
private String FirstName;
private String LastName;
private String Email;
private int age;
private int[] Grades;

public Student(int S_ID ){
    this.setStudentID(S_ID);
}
//Constructor
public Student(int S_ID,String fName,String lName,String email,int Age,
               int[] grade){
    setStudentID(S_ID);
    setFirstName(fName);
    setLastName(lName);
    setEmail(email);
    setAge(Age);
    setGrade(grade);
}
//Accessor Methods (get methods)
public int getStudentID(){
    return StudentID;
}
public String getFirstName(){
    return FirstName;
}
public String getLastName(){
    return LastName;
}
public String getEmail(){
    return Email;
}

public int getAge(){
    return age;
}
public int[] getGrades(){
    return Grades;
}

//Mutator methods (set methods)

public void setStudentID(int StudentID){
    this.StudentID=StudentID;
}
public void setFirstName(String FirstName){
    this.FirstName=FirstName;
}

public void setLastName(String LastName){
    this.LastName=LastName;
}
public void setEmail(String Email){
    this.Email=Email;
}
public void setAge(int age){
    this.age=age;
}
public void setGrade(int Grade[]){
    this.Grades=Grade;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Student student = (Student) o;

    return StudentID == student.StudentID;
}

@Override
public int hashCode() {
    return StudentID;
}
}

and in main area class you can do 在主要的区域课程中,您可以

public class Test {
public static void main(String []args){
    List<Student> list = new ArrayList<>();

    list.add(new Student(1,"a","a","a",1, new int[]{1}));
    list.add(new Student(2,"b","b","b",2, new int[]{2}));
    list.remove(new Student(1));

    list.forEach(System.out::println);

}
}

Output 产量

com.traveliko.platform.web.frontend.Student@2 com.traveliko.platform.web.frontend.Student@2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM