【问题标题】:Delete object in Arraylist删除 Arraylist 中的对象
【发布时间】:2014-10-05 04:36:33
【问题描述】:

我的问题是,当我在数组中有 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);

}

【问题讨论】:

  • 您应该了解do/while 循环和while 循环之间的区别:)
  • @Trafalgar law:对于列表中的两个对象,您应该看到“您确定...?”两次和两次“删除成功”,假设您在循环的每次迭代中按“y”/“Y”并且stud.getStudNum().equals(enterStudNum2)true。你的输出是什么?
  • @Voicu 输出是这样的.. 删除成功确定要删除吗?它要求另一次确认,而不仅仅是一次确认
  • @Trafalgarlaw:那应该是因为列表中有另一个对象要删除。确保您输出列表的大小,以了解您将被提示删除多少次。逐步调试也不会受到伤害。
  • @Voicu tnx 我试试看

标签: java arraylist iterator


【解决方案1】:

这是因为那里有两个循环。您的内部循环在 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);

}

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 2013-04-17
    相关资源
    最近更新 更多