Reputation: 73
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());
}
Upvotes: 0
Views: 1033
Reputation: 2551
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());
}
Upvotes: 2
Reputation: 56413
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) {...}
Upvotes: 1
Reputation: 17880
LocalDate.getDayOfWeek
returns an enum of type DayOfWeek
. But you are comparing a String with the enum.
You must do
date.getDayOfWeek() == DayOfWeek.FRIDAY
Upvotes: 3