I am having some issues when deleting an element in one of my arrays.Students is the array I am trying to remove elements from. I am searching elements by each ID. The program works but then I receive an error. I know that I can use the indexOf method to find but that would let me start from scratch from the code that I have. Is there a way to delete an Element from an array with searching from an ID? And if so, is there a way to update the array?
For example
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]
This is my removeStudent method:
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");
this is my main method::-------------------------------------------------------------------------------------------------------------------------------------- so I tried to use the remove.Student(studentId) and it ran fine but when I add students and then try to delete them the error shows up again
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)