删除Arraylist中的对象

时间:2014-10-05 04:36:33

标签: 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?");
        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);

}

1 个答案:

答案 0 :(得分:0)

因为那里有两个循环。在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);

}