Skip to content
Advertisement

Why wrong greeting is coming in Java [closed]

I wanted to make a program that greets you according to the time of day . I live in India so the zoneid that I used was Asia/Kolkata The timezone here is IST(GMT+5:30). And while I am writing this question the time here is 12:49 PM . Still this print the output good night idk what is wrong with the code . THE CODE IS ==

LocalDateTime today = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
int h_today = today.getHour();
if(h_today > 0 && h_today < 12)
     { 
     System.out.println("Good morning ma'am! n"); 
     }
     else if(h_today > 12 && h_today < 17)
     { 
     System.out.println("Good afternoon ma'am! n"); 
     }
     else if( h_today >17 && h_today < 23 )
     {
     System.out.println("Good evening ma'am! n"); 
     }
     else 
     {
      System.out.println("Good night ma'am! n"); 
     }

I used LocalDateTime instead of LocalTime because I need to do some more operations also and I think that shouldn’t have affected the output . I think the problem is with the conditions that I gave . Please help me ☆

Advertisement

Answer

If the hour is 12, it is not present in any of the if statements. So the control is going to else. Put >= instead of >. Change

else if(h_today > 12 && h_today < 17)

to

else if(h_today >= 12 && h_today < 17)

similarly for others.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement