从数组中通过ID删除一个元素。

huangapple go评论70阅读模式
英文:

Deleting an element from an array using an ID

问题

I am having some issues when deleting an element in one of my arrays. Students 是我正在尝试从中删除元素的数组。我正在按每个 ID 搜索元素。程序是有效的,但是后来我收到了一个错误。我知道可以使用 indexOf 方法来查找,但那样会让我从现有的代码重新开始。有没有一种方法可以通过从 ID 进行搜索来从数组中删除元素?如果可以,是否有一种方法可以更新数组?

例如:

private final ArrayList<Student> students;
students.add(1)//将数字视为 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("已删除包含 " + studentId + " 信息的个人资料:");
//                this.students.remove(studentId);//这是我最初使用的会导致错误但能运行的方法
                this.students.removeIf(student -> student.getId().equals(studentId));//这是我从另一个回答中获取的方法,但不起作用。
            }
        }
        System.out.println("找不到具有该 ID 的个人资料");
}

这是我的 main 方法:-------------------------------------------------- 所以我尝试使用 removeStudent(studentId),它运行得很好,但是当我添加学生然后尝试删除他们时,错误再次出现。

public static void deleteStudentID() {
        System.out.println("请输入您的学生 ID 以搜索您的个人资料");
        int searchId = scanner.nextInt();//要求用户插入 ID
        institution.removeStudent(searchId);//在数组中查找班级并搜索 ID

        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)
英文:

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&lt;Student&gt; 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 &lt; students.size(); i++) {
            if (students.get(i).getId() == studentId) {

                System.out.println(&quot;Deleted a profile containing information for &quot; + studentId + &quot;:&quot;);
//                this.students.remove(studentId);//this is the first one I used that gave me an error but ran
                this.students.removeIf(student -&gt; student.getId().equals(studentId));//this one I got from another response but does not work.
            }
        }
        System.out.println(&quot;Could not find profile with that ID&quot;);

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(&quot;Please enter your student ID to search for your profile&quot;);
        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 &quot;main&quot; 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)

答案1

得分: 3

考虑使用一个 map 来按照学生的 ID 存储每个学生:

Map<Integer, Student> students = new HashMap<>();

// 如果找到学生并删除成功,则返回 true;否则返回 false
public boolean removeStudent(int studentId) {
    return students.remove(studentId) == null ? false : true;
}
英文:

Consider using a map to store each student by ID:

Map&lt;Integer, Student&gt; students = new HashMap&lt;&gt;();

// returns true if student found and deleted, false otherwise
public boolean removeStudent(int studentId) {
    students.remove(studentId) == null ? false : true;
}

答案2

得分: 1

以下是您要翻译的内容:

出现错误 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1602488517 out of bounds for length 2 的原因是您通过 studentId 而不是 index 从数组中移除了一个学生:

removeStudent 更改为以下内容:

    public void removeStudent(int studentId) {

        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getId() == studentId) {

                System.out.println("删除包含信息的配置文件:" + studentId + ":");
                this.students.remove(i);
            }
        }
        System.out.println("找不到具有该 ID 的配置文件");
    }
英文:

The reason you are getting this error Exception in thread &quot;main&quot; java.lang.IndexOutOfBoundsException: Index 1602488517 out of bounds for length 2 is because you remove a student in the array by the studentId instead of the index:

change removeStudent to this:

    public void removeStudent(int studentId) {

      for (int i = 0; i &lt; students.size(); i++) {
          if (students.get(i).getId() == studentId) {

              System.out.println(&quot;Deleted a profile containing information for 
                   &quot; + studentId + &quot;:&quot;);
              this.students.remove(i);
          }
      }
      System.out.println(&quot;Could not find profile with that ID&quot;);
    }

huangapple
  • 本文由 发表于 2020年8月31日 12:29:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63664793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定