gpt4 book ai didi

java - 数组列表错误

转载 作者:行者123 更新时间:2023-12-01 06:50:42 25 4
gpt4 key购买 nike

ArrayList aList = new ArrayList();

public void AddPerson() {
String n = JOptionPane.showInputDialog(null, "Please Enter Name");
String a = JOptionPane.showInputDialog(null, "Please Enter Name");
String p = JOptionPane.showInputDialog(null, "Please Enter Name");
PersonInfo person = new PersonInfo(n, a, p);
aList.add(person);
}

public void Search(String n) {
for (int i = 0; i <= aList.size(); i++) {
PersonInfo person = (PersonInfo) aList.get(i);
if (n.equals(person.name)) {
person.PrintInfo();

}

}

}

public void remove(String n) {
for (int i = 0; i <= aList.size(); i++) {
PersonInfo person = (PersonInfo) aList.get(i);
if (n.equals(person.name)) {
aList.remove(i);

}

}

}
}

搜索和删除功能不起作用。我每次都会收到错误消息:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.get(ArrayList.java:429) at lec06.AddressBook.Search(AddressBook.java:29) at lec06.Lec06.main(Lec06.java:33)

最佳答案

显然你的列表是空的(你使用了 AddPerson() 函数吗?)。

在您的 for-loop 中您有以下情况:i <= aList.size() 。所以即使aList size 等于 0(列表为空),您将尝试从该列表中获取一个元素 ( get(i) )。这就是为什么你会得到异常(exception)。

您应该更改i <= aList.size()i < aList.size()来解决这个问题。

关于java - 数组列表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com