首页 > 解决方案 > 即使不满足 If-Statement,Java ArrayList 也会始终删除对象

问题描述

我正在尝试构建一种方法来检查房间是否已经在某个时间被预订,如果是,它应该告诉用户房间已经被预订。问题是该方法总是删除一个有预订的房间,即使房间在选定的时间是空闲的。因此,如果我从下午 2 点到下午 3 点预订房间,然后尝试从下午 4 点到下午 5 点预订,它仍然会从我的可用房间中删除该房间。不知何故,我的 if 语句似乎总是正确的,即使它不应该如此。

说明:用户应该通过控制台输入日期(我仍然是初学者,这是一个大学项目,如果有任何愚蠢的错误,我很抱歉,也没有使用数据库)。日期保存在 dateB(预订开始)和 dateE(结束)中。我将之前创建的所有房间保存在 ArrayList 中,然后将它们保存在第二个房间(availabeRooms)中,以便我可以在请求的时间删除已经预订的房间。这一切都很好,除了 if 语句由于某种原因总是正确的。它应该只删除在这个特定时间已经预订的房间。

    Date dateB = null;
    Date dateE = null;
    System.out.println("Please enter the beginning of your booking (yyyy-MM-dd HH:mm): ");
    String enter = sc.nextLine();
    try
    {
        dateB = f.parse(enter);
    }catch(
    ParseException e)
    {
        e.printStackTrace();
    }
    System.out.println("Please enter the end of your booking: ");
    try
    {
        dateE = f.parse(sc.nextLine());
    }catch(
    ParseException e)
    {
        e.printStackTrace();
    }
     ArrayList<Room> availabeRooms = new ArrayList<Room>(); 
        for(Room r : rc.getRoomContainer()){
            availableRooms.add(r);
        }   
        for (Booking bk : this.bookings) {
            if (!dateB.before(bk.getBeginning()) && !dateE.before(bk.getBeginning()) 
                || !dateB.after(bk.getEnd()) && !dateE.after(bk.getEnd())) {
                for (Room r : rc.getRoomContainer()) {
                    if (bk.getRoom().equals(r)) {
                        availableRooms.remove(r);
                }
            }

        }
    }

标签: javaif-statementarraylist

解决方案


You have your if conditions all wrong, for instance if a room is booked for today and I ask for a room tomorrow then the first part of the condition !dateB.before(bk.getBeginning()) && !dateE.before(bk.getBeginning() will return true which is not what you want. Using negations often makes things harder

Look at it this way, a room is not available if the requested date time (dateB-DateE) somehow overlaps an existing booking. So I would create a private method that takes a date and a booking and returns true if the date is between getBeginning() and getEnd() and then call that method in the if (...) clause for both dateB and dateE to determine if a booking exists for that time period.


推荐阅读