我在主ArrayList中创建了一个class.Also类型的LocalDate,它是一个包含LocalDate变量、getter和setter的类。总的来说,我创建了一个布尔标志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");
}
}发布于 2019-05-08 12:36:18
您从不在列表中添加任何实例。根据你的期望:
scanner.nextInt();,它打印了2019-5-3和"Didn't found a same date."scanner.nextInt();,它打印了2019-5-6和"Didn't found a same date."scanner.nextInt(); --它打印了2019-5-3和"Didn't found a same date." --我希望得到一条“同一日期发现”的消息。您需要的是当flight是真的时候插入一个theDay,当没有匹配的出发日期时。
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;
}
}发布于 2019-05-08 12:37:40
之所以会出现这种情况,是因为您没有将您的航班添加到您的flightList中,所以它总是空的。在if语句中,更改代码以在未找到日期时添加航班:
if (theDay){
System.out.println("Didn't found a same day.");
flightList.add(flight);
} else {
System.out.println("A same date found");
}https://stackoverflow.com/questions/56040714
复制相似问题