I have problem with my program, in which I have to insert a random date (dd/MM/yyyy) and if the day is Friday or Saturday, it should print out "It's time for party". I insert dates with Friday or Satuday, but it still print's out "You should study". Can somebody help out?
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(input, formatter);
System.out.println(date.getDayOfWeek().name());
if (date.getDayOfWeek().equals("FRIDAY")) {
System.out.println("Time for party, because it is: " + date.getDayOfWeek());
}
else if (date.getDayOfWeek().equals("SATURDAY"))
System.out.println("Time for party, because it is: " + date.getDayOfWeek());
else {
System.out.println("You should study! It is: " + date.getDayOfWeek());
}
LocalDate.getDayOfWeek
returns an enum of type DayOfWeek
. But you are comparing a String with the enum.
You must do
date.getDayOfWeek() == DayOfWeek.FRIDAY
You're comparing a DayOfWeek
instance with a String
instance so they will never be equal as they are different types.
one solution is to call toString
prior to calling equals:
if (date.getDayOfWeek().toString().equals("FRIDAY")){...}
or better use:
if (date.getDayOfWeek() == DayOfWeek.FRIDAY) {...}
You should replace string value to enum type DayOfWeek.FRIDAY or DayOfWeek.SATURDAY . As you comparing string with enum.
if (date.getDayOfWeek().equals(DayOfWeek.FRIDAY)) {
System.out.println("Time for party, because it is: " + date.getDayOfWeek());
}
else if (date.getDayOfWeek().equals(DayOfWeek.SATURDAY))
System.out.println("Time for party, because it is: " + date.getDayOfWeek());
else {
System.out.println("You should study! It is: " + date.getDayOfWeek());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.