gpt4 book ai didi

java - 更新arraylist中的元素,还有比这更好的方法吗?

转载 作者:行者123 更新时间:2023-12-01 21:55:04 30 4
gpt4 key购买 nike

我正在使用 swing 制作一个简单的应用程序,对于数组列表和列表迭代器我是新手。我想做的是一个按钮,允许您更新数组列表中人员的信息。我应该在不使用 for 或 for-each 循环的情况下执行此操作。这是我的代码:

String searchedName = JOptionPane.showInputDialog(null, "Type in the first name of the person you want to update:");
ListIterator<Student> listIt = peopleArray.listIterator();
while(listIt.hasNext()){
String firstname = listIt.next().getFirstname();
if(searchedName.equalsIgnoreCase(firstname){
String newFirstname = JOptionPane.showInputDialog(null, "Input new first name:");
String newLastname = JOptionPane.showInputDialog(null, "Type in new last name:");
String newEmail = JOptionPane.showInputDialog(null, "Type in new email:");
String newOccupation = JOptionPane.showInputDialog(null, "Type in new occupation:");
listIt.previous().setFirstname(newFirstname);
listIt.next().setLastname(newLastname);
listIt.previous().setEmail(newEmail);
listIt.next().setOccupation(newOccupation);
}
}

这段代码可以工作,但看起来很奇怪。我是否必须像这样跳回第四个(listIt.next()然后listIt.previous())还是有更好的方法?

//N

最佳答案

你不必来回跳转,确保只调用一次 next() 。这个怎么样:

    String searchedName = JOptionPane.showInputDialog(null, "Type in the first name of the person you want to update:");
ListIterator<Student> listIt = peopleArray.listIterator();
while(listIt.hasNext()){
Student studentToUpdate = listIt.next();
if(searchedName.equalsIgnoreCase(studentToUpdate.getFirstname()){
String newFirstname = JOptionPane.showInputDialog(null, "Input new first name:");
String newLastname = JOptionPane.showInputDialog(null, "Type in new last name:");
String newEmail = JOptionPane.showInputDialog(null, "Type in new email:");
String newOccupation = JOptionPane.showInputDialog(null, "Type in new occupation:");
studentToUpdate.setFirstname(newFirstname);
studentToUpdate.next().setLastname(newLastname);
studentToUpdate.setEmail(newEmail);
studentToUpdate.setOccupation(newOccupation);
}
}

关于java - 更新arraylist中的元素,还有比这更好的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34498510/

30 4 0