我用swing创建了一个简单的应用程序,当涉及到arraylists和listiterator时,我是新手。我正在尝试做的是一个按钮,该按钮可让您更新有关数组列表中人员的信息。我应该这样做,而无需使用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);
            }
        }

09-10 22:09