我在 Main 类中创建了一个 Flight 类型的 ArrayList。Flight 也是一个包含 LocalDate 变量、getter 和 setter 的类。在 main 中,我创建了一个 boolean 标志 theDay 并设置为 true。我希望当 For 循环找到与之前相同的 LocalDate 日期值时,此标志更改为 false。 例如:
第一次尝试:我将值 3 放入 Scanner.nextInt() 中; 它打印了 2019-5-3 和“没有找到相同的日期。”
第二次尝试:我将值 6 放入 Scanner.nextInt() 中; 它打印了 2019-5-6 和“没有找到相同的日期。”
第三次尝试:我再次将值 3 放入 Scanner.nextInt() 中; 它打印了 2019-5-3 和“没有找到相同的日期”。 我预计会收到“找到相同日期”的消息。
public static void main(String[] args) {
ArrayList<Flight> flightList = new ArrayList<Flight>();
Scanner scanner = new Scanner(System.in);
int counter=1;
while (counter <= 3) {
Flight flight = new Flight();
System.out.println("Give the day of the departure.");
LocalDate day = LocalDate.of(2019, Month.MAY, scanner.nextInt());
flight.setDateOfDeparture(day);
System.out.println(flight.getDateOfDeparture());
boolean theDay = true; //Flag (reversed way in order to achieve the TRUE logic value).
for (Flight flight1 : flightList) {
System.out.println(flight1.getDateOfDeparture());
if (flight1.getDateOfDeparture().compareTo(flight.getDateOfDeparture()) == 0) {
theDay = false;
}
}
counter++;
if (theDay){
System.out.println("Didn't found a same day.");
}else
System.out.println("A same date found");
}
}
最佳答案
您永远不会在列表中添加任何实例。 根据您的期望:
- 第一次尝试:我将值 3 放入
scanner.nextInt();
它打印了2019-5-3
和"Didn't found a same date."
- 第二次尝试:我输入了值
6进
scanner.nextInt();
它打印了2019-5-6
和"Didn't found a same date."
- 第三次尝试:我再次将值 3 放入
scanner.nextInt();
它打印了2019-5-3
和"Didn't found a same date."
我预计会收到“找到相同日期”的消息。
您需要插入 flight
当 theDay
当没有匹配的出发日期时为 true。
if (theDay){
flightList.add(flight);
System.out.println("Didn't found a same day.");
}else{
System.out.println("A same date found");
}
<小时/>
当您准备好继续前进时,您可以使用 Set<Flight>
具有正确的等效实现
您永远不需要检查自己是否已经存在“等效”实例,Set
将为您做。
您所需要做的就是实现equals
和hashCode
正确的话你的代码将看起来像:
Set<Flight> flights = new HashSet<>();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 5; ++i){
Flight f = new Flight();
f.setDeparture(LocalDate.of(2019, Month.MAY, sc.nextInt()));
if(flights.add(f)){
System.out.println("New flight added");
} else {
System.out.println("Flight already booked");
}
}
sc.close();
为了给你一个想法,这里是 eclipse 为一个简单的类生成的方法
class Flight {
LocalDate departure;
public void setDeparture(LocalDate departure) {
this.departure = departure;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((departure == null) ? 0 : departure.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Flight other = (Flight) obj;
if (departure == null) {
if (other.departure != null)
return false;
} else if (!departure.equals(other.departure))
return false;
return true;
}
}
关于java - 为什么两个 LocalDate 变量之间的比较不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56040714/