For loop为什么没有正确将元素添加到ArrayList对象中?

huangapple go评论77阅读模式
英文:

Why is For loop not correctly adding elements to the arraylist object?

问题

以下是代码的中文翻译部分:

// 检查日期和时间输入是否在正确的格式中
if (dateMatcher.matches() && timeMatcher.matches()) {
    // 将日期输入和时间输入连接起来,创建一个格式为 "MM/dd/yyyy HH:mm" 的日期时间字符串

    // 将连接后的日期时间输入转换为 Date 对象
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    Date dateTime = null;
    LocalDateTime ldt = null;
    try {
        dateTime = sdf.parse(dateInput + " " + startTimeInput);
        ldt = dateTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    } catch (ParseException e) {
        // 处理异常
    }

    // 检查组合的日期时间是否在未来
    assert dateTime != null;
    if (dateTime.after(new Date())) {
        // 获取医生在 doctorArrayList 中的索引
        int selectedIndex = doctorComboBox.getSelectedIndex();
        // 从 doctorArrayList 中获取所选医生对象
        Doctor selectedDoctor = doctorArrayList.get(selectedIndex);

        // 检查所选医生在指定日期和时间是否可用
        if (selectedDoctor.isAvailable(selectedDoctor, ldt, Integer.parseInt(hourCountInput), Consultation.getConsultationList())) {
            JOptionPane.showMessageDialog(null, "所选医生在指定日期和时间可用。");

            // 关闭当前窗口
            setVisible(false);
            dispose();

            // 打开患者详情页面
            GUIPatientDetailsPage patientDetailsPage = new GUIPatientDetailsPage();
            patientDetailsPage.patientDetailsPage(ldt, selectedIndex, hourCountInput);
        } else {
            // 如果医生不可用,请创建可用医生列表
            List<Doctor> availableDoctors = new ArrayList<>();
            for (Doctor doc : doctorArrayList) {
                if (doc.isAvailable(selectedDoctor, ldt, Integer.parseInt(hourCountInput), Consultation.getConsultationList())) {
                    availableDoctors.add(doc);
                }
            }
            if (availableDoctors.isEmpty()) {
                System.out.println("无医生可用");
            }

            if (!availableDoctors.isEmpty()) {
                // 如果有可用医生,随机选择其中之一
                Random rand = new Random();
                int index = rand.nextInt(availableDoctors.size());
                Doctor newSelectedDoctor = availableDoctors.get(index);

                // 打开患者详情页面
                GUIPatientDetailsPage patientDetailsPage = new GUIPatientDetailsPage();
                patientDetailsPage.patientDetailsPage(ldt, index, hourCountInput);

                // 显示确认消息
                JOptionPane.showMessageDialog(null, "您选择的医生在该时间不可用,但我们已选择其他可用医生。请在下方输入您的详细信息。");
            }
        }
    }
}

isAvailable 方法如下:

public boolean isAvailable(Doctor doctor, LocalDateTime startTime, int duration, List<Consultation> consultationList) {
    for (Consultation consultation : consultationList) {
        // 检查所需咨询的开始时间是否在现有咨询的持续时间内
        if (startTime.isAfter(consultation.getDateTime()) && startTime.isBefore(consultation.getDateTime().plusHours(consultation.getHourCount()))) {
            return false;
        }

        // 检查所需咨询的结束时间是否在现有咨询的持续时间内
        LocalDateTime endTime = startTime.plusHours(duration);
        if (endTime.isAfter(consultation.getDateTime()) && endTime.isBefore(consultation.getDateTime().plusHours(consultation.getHourCount()))) {
            return false;
        }

        // 检查所需咨询的医生是否与现有咨询的医生相同
        if (doctor == consultation.getDoctor()) {
            return false;
        }
    }
    return true;
}

希望这些翻译能帮助您更好地理解代码。如果您有任何问题或需要进一步的帮助,请随时告诉我。

英文:

I'm doing a consultation center program a part of it is to select a doctor and enter the start time then enter for how many hours then check if the selected doctor already has a booked appointment at that time and if he has a appointment the program checks for other doctors who doesn't have a appointment at that time period and assign a doctor from available doctors randomly so. I created the program but the problem is if a consultation is not available the program identifies it but it doesn't randomly assign a doctor.

here is my code,

// Check if both the date and time inputs are in the correct format
if (dateMatcher.matches() &amp;&amp; timeMatcher.matches()) {
// Concatenate the date input and time input to create a combined date-time string in the format &quot;MM/dd/yyyy HH:mm&quot;
// Convert the combined date-time input to a Date object
SimpleDateFormat sdf = new SimpleDateFormat(&quot;yyyy/MM/dd HH:mm&quot;);
Date dateTime = null;
LocalDateTime ldt = null;
try {
dateTime = sdf.parse(dateInput + &quot; &quot; + startTimeInput);
ldt = dateTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
} catch (ParseException e) {
// Handle the exception
}
// Check if the combined date-time is in the future
assert dateTime != null;
if (dateTime.after(new Date())) {
// Get the index of the selected doctor in the doctorArrayList
int selectedIndex = doctorComboBox.getSelectedIndex();
// Get the selected doctor object from the doctorArrayList
Doctor selectedDoctor = doctorArrayList.get(selectedIndex);
// Check if the selected doctor is available at the specified date and time
if (selectedDoctor.isAvailable(selectedDoctor, ldt, Integer.parseInt(hourCountInput), Consultation.getConsultationList())) {
JOptionPane.showMessageDialog(null, &quot;The selected doctor is available at the specified date and time.&quot;);
// Close the current frame
setVisible(false);
dispose();
// Open the patient details page
GUIPatientDetailsPage patientDetailsPage = new GUIPatientDetailsPage();
patientDetailsPage.patientDetailsPage(ldt, selectedIndex, hourCountInput);
} else {
// If the doctor is not available, create a list of available doctors
List&lt;Doctor&gt; availableDoctors = new ArrayList&lt;&gt;();
for (Doctor doc : doctorArrayList) {
if (doc.isAvailable(selectedDoctor, ldt, Integer.parseInt(hourCountInput), Consultation.getConsultationList())) {
availableDoctors.add(doc);
}
}
if (availableDoctors.isEmpty()) {
System.out.println(&quot;empty&quot;);
}
if (!availableDoctors.isEmpty()) {
// If there are available doctors, randomly select one of them
Random rand = new Random();
int index = rand.nextInt(availableDoctors.size());
Doctor newSelectedDoctor = availableDoctors.get(index);
// Open the patient details page
GUIPatientDetailsPage patientDetailsPage = new GUIPatientDetailsPage();
patientDetailsPage.patientDetailsPage(ldt, index, hourCountInput);
// Display a confirmation message
JOptionPane.showMessageDialog(null, &quot;The Doctor you selected is not available at that time,But we have selected another doctor available at that time. Please enter your details below&quot;);
}
} //else {
// If there are no available doctors, display an error message
// JOptionPane.showMessageDialog(null, &quot;Sorry, there are no doctors available at the specified date and time. Please try again.&quot;);
// }
}
}
});

And isAvailable method is here,

    public boolean isAvailable(Doctor doctor, LocalDateTime startTime, int duration, List&lt;Consultation&gt; consultationList) {
for (Consultation consultation : consultationList) {
// Check if the start time of the desired consultation falls within the duration of an existing consultation
if (startTime.isAfter(consultation.getDateTime()) &amp;&amp; startTime.isBefore(consultation.getDateTime().plusHours(consultation.getHourCount()))) {
return false;
}
// Check if the end time of the desired consultation falls within the duration of an existing consultation
LocalDateTime endTime = startTime.plusHours(duration);
if (endTime.isAfter(consultation.getDateTime()) &amp;&amp; endTime.isBefore(consultation.getDateTime().plusHours(consultation.getHourCount()))) {
return false;
}
// Check if the doctor of the desired consultation is the same as the doctor of an existing consultation
if (doctor == consultation.getDoctor()) {
return false;
}
}
return true;
}

For loop为什么没有正确将元素添加到ArrayList对象中?

in this input there's already appointment to this doctor in this time period so it should check and tell me if the appointment is available. if not it has to assign a random doctor then display a message.

This is what happens when I click submit.

For loop为什么没有正确将元素添加到ArrayList对象中?

it doesn't do anything from what I suspected was that with this for loop is not adding anything to availableDoctors list

     // If the doctor is not available, create a list of available doctors
List&lt;Doctor&gt; availableDoctors = new ArrayList&lt;&gt;();
for (Doctor doc : doctorArrayList) {
if (doc.isAvailable(selectedDoctor, ldt, Integer.parseInt(hourCountInput), Consultation.getConsultationList())) {
availableDoctors.add(doc);
}
} 

So i added this part to verify,

if (availableDoctors.isEmpty()) {
System.out.println(&quot;empty&quot;);
}

and I was right it printed empty.

What can I do to make this correct?

答案1

得分: 1

Criteria 1

在循环中,如果您的 startTime 在咨询期间,不管您正在寻找的是否是该医生,您都会返回 false。因此,例如,如果您正在寻找 doctor1 的可用性,但循环的第一次迭代找到 doctor2 的咨询,他在您选择的 startTime 不可用,然后您会 - 不正确地 - 得出 doctor1 不可用的结论。

Criteria 2

在循环中,如果您的 endTime 在咨询期间,不管您正在寻找的是否是该医生,您都会返回 false。因此,例如,如果您正在寻找 doctor1 的可用性,但循环的第一次迭代找到 doctor2 的咨询,他在您选择的 endTime 不可用,然后您会 - 不正确地 - 得出 doctor1 不可用的结论。

Criteria 3

如果医生是您正在寻找的医生,您会返回 false。因此,如果您想要给一个医生预约,即使它不与您的时间段重叠,false 也会被返回。

Solution

您需要避免仅因为医生与您搜索的医生匹配就返回真值,因为我们不关心医生是否有任意的预约,而是关心医生是否在搜索时间内有预约。相反,将这个条件包装在其他两个条件周围,如下所示:

public boolean isAvailable(Doctor doctor, LocalDateTime startTime, int duration, List<Consultation> consultationList) {
    for (Consultation consultation : consultationList) {
        if (doctor == consultation.getDoctor()) {
            // Check if the start time of the desired consultation falls within the duration of an existing consultation
            if (startTime.isAfter(consultation.getDateTime()) && startTime.isBefore(consultation.getDateTime().plusHours(consultation.getHourCount()))) {
                return false;
            }

            // Check if the end time of the desired consultation falls within the duration of an existing consultation
            LocalDateTime endTime = startTime.plusHours(duration);
            if (endTime.isAfter(consultation.getDateTime()) && endTime.isBefore(consultation.getDateTime().plusHours(consultation.getHourCount()))) {
                return false;
            }
        }
    }
    return true;
}

您还可以通过陈述如果不是 startTime 晚于咨询的结束时间或 endTime 早于咨询的开始时间,则返回 false 来简化您的条件,但我避免了这种重构,以保持代码接近您的初始版本。

英文:

You are looping through consultations and you return false at the first unavailability. However, you do not correctly check this.

Criteria 1

You are returning false if your startTime is during a consultation, independently of whether that doctor is the one you are searching for. So, for instance, if you are searching for the availability of doctor1, but the first iteration of the loop finds a consultation of doctor2, who is not available at the startTime of your choice, then you conclude - incorrectly - that doctor1 is unavailable.

Criteria 2

You are returning false if your endTime is during a consultation, independently of whether that doctor is the one you are searching for. So, for instance, if you are searching for the availability of doctor1, but the first iteration of the loop finds a consultation of doctor2, who is not available at the endTime of your choice, then you conclude - incorrectly - that doctor1 is unavailable.

Criteria 3

You are returning false for availability if the doctor is the same you are searching for. So, if you want an appointment to a doctor who has an appointment at any time, even if it does not overlap your time interval, then false will be returned.

Solution

You need to avoid returning a truth value just because the doctor matches your searched doctor, because we are not interested in whether the doctor has some arbitrary appointments, but we are interested whether the doctor has an appointment at the time in search. Instead, wrap this if around the two other criterias, like below:

    public boolean isAvailable(Doctor doctor, LocalDateTime startTime, int duration, List&lt;Consultation&gt; consultationList) {
for (Consultation consultation : consultationList) {
if (doctor == consultation.getDoctor()) {
// Check if the start time of the desired consultation falls within the duration of an existing consultation
if (startTime.isAfter(consultation.getDateTime()) &amp;&amp; startTime.isBefore(consultation.getDateTime().plusHours(consultation.getHourCount()))) {
return false;
}
// Check if the end time of the desired consultation falls within the duration of an existing consultation
LocalDateTime endTime = startTime.plusHours(duration);
if (endTime.isAfter(consultation.getDateTime()) &amp;&amp; endTime.isBefore(consultation.getDateTime().plusHours(consultation.getHourCount()))) {
return false;
}
}
}
return true;
}

You can also simplify your criteria by stating that if it's not true that startTime is later than the end time of the consultation or endTime is earlier than the start time of the consultation, then return false, but I avoided doing that refactor to keep the code close to your initial version.

huangapple
  • 本文由 发表于 2023年1月8日 22:40:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定