【发布时间】:2020-08-31 14:13:45
【问题描述】:
我在删除其中一个数组中的元素时遇到了一些问题。Students 是我要从中删除元素的数组。我正在按每个 ID 搜索元素。该程序有效,但随后我收到错误消息。我知道我可以使用 indexOf 方法来查找,但这会让我从我拥有的代码从头开始。有没有办法通过从 ID 搜索从数组中删除元素?如果是这样,有没有办法更新数组?
例如
private final ArrayList<Student> students;
students.add(1)//consider nums as ID
students.add(2)
students.add(3)
students = [1,2,3]
students.remove[1]
students = [2,3]
这是我的 removeStudent 方法:
public void removeStudent(int studentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() == studentId) {
System.out.println("Deleted a profile containing information for " + studentId + ":");
// this.students.remove(studentId);//this is the first one I used that gave me an error but ran
this.students.removeIf(student -> student.getId().equals(studentId));//this one I got from another response but does not work.
}
}
System.out.println("Could not find profile with that ID");
这是我的 main 方法::-------------------------------- -------------------------------------------------- -------------------------------------------------- - 所以我尝试使用 remove.Student(studentId) 并且运行良好,但是当我添加学生然后尝试删除他们时,错误再次出现
public static void deleteStudentID() {
System.out.println("Please enter your student ID to search for your profile");
int searchId = scanner.nextInt();//asks user to insert an ID
institution.removeStudent(searchId);//finds the class and searches the Id in array
showOptions();
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1602488517 out of bounds for length 2
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.remove(ArrayList.java:503)
at Institution.removeStudent(Institution.java:133)
at Main.deleteStudentID(Main.java:237)
at Main.deleteID(Main.java:220)
at Main.main(Main.java:35)
【问题讨论】:
-
我不明白这是在告诉我什么
标签: java arrays intellij-idea