java 将从组合框获取的值与另一个字符串进行比较失败,即使两者看起来相同

w41d8nur  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(44)

我试图从3个独立的组合框中获取一个日期,然后将其转换为int并创建一个Date对象。然而,当我将此日期字符串与一个已经存在的字符串进行比较时,它不匹配,即使在调试器中它看起来是相同的。我设置了一个简单的if语句来检查问题是什么,但我不确定为什么它不匹配。

int apptDay, apptMonth, apptYear;
apptDay = Integer.parseInt(consultationDay.getSelectedItem().toString());
apptMonth = Integer.parseInt(consultationMonth.getSelectedItem().toString());
apptYear = Integer.parseInt(consultationYear.getSelectedItem().toString());
consultationDate = new Date(apptDay, apptMonth, apptYear);


if (appointmentList.get(0).getDate() == consultationDate) {
    sopl("Working");
}

我很确定我的代码中有一些与组合框相关的问题,因为这是我唯一遇到问题的地方。if语句从未被满足,所以“Working”从未被打印出来。
任何帮助都将不胜感激。

qcbq4gxm

qcbq4gxm1#

您应该使用**.equlas()**而不是==运算符。

int apptDay = 5, apptMonth = 12, apptYear = 2000;
Date testDate = new Date(apptDay, apptMonth, apptYear);
Date consultationDate = new Date(apptDay, apptMonth, apptYear);

if (testDate == consultationDate) {
    System.out.println("Success for ==");
} else if (testDate.equals(consultationDate)) {
    System.out.println("Success for equals");
}

相关问题