如何从StudentID中删除arrayList中的项目?

时间:2017-05-07 03:02:36

标签: java arraylist

我需要编写一个方法,通过学生ID从ArrayList(myRoster)中删除学生。如果学生ID不存在,则该方法应打印一条错误消息,指出未找到该ID。我写了一个删除方法,我可以通过索引删除项目。错误消息“找不到ID 3的学生”返回6次(第一次删除3次,第二次错误消息3次)。但是我希望得到一个错误消息,我在main方法中调用第二个删除方法。一点帮助将不胜感激。

学生班级

 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; 
    }

}

名册等级

 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");
              }
          }
    }


    }

}

5 个答案:

答案 0 :(得分:2)

  1. 您应该从不尝试在迭代时从列表中删除元素。
  2. 您的比较不正确,原因是您要将for循环控制变量i与参数StudentID进行比较,而应该是if(myRoster.get(i).getStudentID == StudentID)
  3. 为什么文本&#34; ID&#34; + StudentID +&#34;未找到&#34; 多次打印到控制台是因为您已将其插入循环内,这意味着每次参数StudentID与该值不匹配时它被比较,它将打印相同的消息...

    要完成您的任务,您只需使用ArrayList#removeIf方法删除指定Student的{​​{1}},否则如果ArrayList#removeIf返回false,则可以打印适当的消息,如下面的解决方案所示。

    StudentID

答案 1 :(得分:0)

你的问题似乎是你的remove()方法中的循环不是在studentID上循环,而是循环索引。你应该遍历studentIDs。每次ID与给定ID不匹配时,您的代码都会打印出来。这就是您获得多条打印消息的原因。如果没有人匹配,你应该只打印(即名单大小不会改变)。

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");       
   }     

}

答案 2 :(得分:0)

您也可以使用 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");
}

答案 3 :(得分:0)

您的删除方法目前为列表中没有所需学生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"); }

只要索引i的学生没有所需的ID,就会调用该打印语句,而不是在没有学生拥有该ID的情况下。 解决此问题的一种简单方法是在方法的开头放置boolean并将其设置为false。然后,在if (i == StudentID)块中,删除学生并将值设置为true。然后,在循环完成后,检查布尔值是否为真;如果确实如此,那么所需的学生已被删除。如果它仍然是假的,则没有具有所需ID的学生。

看起来应该是这样的:

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");
}

答案 4 :(得分:0)

是的,你可以这样做,请在学生班上添加一些东西

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;
}
}

在主要区域课程中你可以做到

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);

}
}

<强>输出

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