Java 删除Arraylist中的对象

Java 删除Arraylist中的对象,java,arraylist,iterator,Java,Arraylist,Iterator,我这里的问题是,当我在数组中有2个对象时,它循环2x然后请求另一个对象。你确定要删除它吗?。我搞不懂我的循环。代码如下: for (Iterator<Student> it = student.iterator(); it.hasNext();) { Student stud = it.next(); do { System.out.print("Are you sure you want to delete it?"); Strin

我这里的问题是,当我在数组中有2个对象时,它循环2x然后请求另一个对象。你确定要删除它吗?。我搞不懂我的循环。代码如下:

for (Iterator<Student> it = student.iterator(); it.hasNext();) {

    Student stud = it.next();
    do {
        System.out.print("Are you sure you want to delete it?");
        String confirmDelete = scan.next();

        ynOnly = false;

        if (confirmDelete.equalsIgnoreCase("Y")
                && stud.getStudNum().equals(enterStudNum2)) {
            it.remove();
            System.out.print("Delete Successful");
            ynOnly = false;
        } else if (confirmDelete.equalsIgnoreCase("N")) {
            System.out.print("Deletion did not proceed");
            ynOnly = false;
        } else {
            System.out.println("\nY or N only\n");
            ynOnly = true;
        }
    } while (ynOnly == true);

}

这是因为那里有两个循环。在ynOnly的值变为false后,内部循环终止,但外部循环仍然继续。你可能想要这样的东西-

for (Iterator<Student> it = student.iterator(); it.hasNext();) {

Student stud = it.next();
if(!stud.getStudNum().equals(enterStudNum2))
            continue;                            //you want only that student to be deleted which has enterStudNum2 so let other record skip
do {
    System.out.print("Are you sure you want to delete it?");
    String confirmDelete = scan.next();

    ynOnly = false;

    if (confirmDelete.equalsIgnoreCase("Y")
            && stud.getStudNum().equals(enterStudNum2)) {
        it.remove();
        System.out.print("Delete Successful");
        ynOnly = false;
    } else if (confirmDelete.equalsIgnoreCase("N")) {
        System.out.print("Deletion did not proceed");
        ynOnly = false;
    } else {
        System.out.println("\nY or N only\n");
        ynOnly = true;
    }
} while (ynOnly == true);

}

您应该了解do/while循环和while循环之间的区别:@Trafalgar law:对于列表中的两个对象,您应该看到您确定。。。?两次,删除成功两次,假设每次循环都按“y”/“y”,并且stud.getStudNum.equalsenterStudNum2为true。你的输出是什么?@Voicu输出是这样的。。删除成功是否确实要删除它?它要求再次确认,而不是仅仅一次confirmation@Trafalgarlaw:这应该是因为列表中有另一个要删除的对象。确保输出列表的大小,以了解将提示您删除的次数。一步一步地调试也不会有什么坏处。@Voicu tnx我试试看