Advertisement
dimipan80

Beer Time

Aug 6th, 2014
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1. /* A beer time is after 1:00 PM and before 3:00 AM.
  2.  * Write a program that enters a time in format “h:mm tt” (an hour in range [01...12],
  3.  * a minute in range [00…59] and AM / PM designator) and prints “beer time”
  4.  * or “non-beer time” according to the definition above or “invalid time”
  5.  * if the time cannot be parsed. Note that you may need to learn how to parse dates and times. */
  6.  
  7. import java.time.LocalTime;
  8. import java.time.format.DateTimeFormatter;
  9. import java.util.Locale;
  10. import java.util.Scanner;
  11.  
  12. public class BeerTime {
  13.  
  14.     public static void main(String[] args) {
  15.         // TODO Auto-generated method stub
  16.         Locale.setDefault(Locale.ROOT);
  17.         Scanner scan = new Scanner(System.in);
  18.         System.out.print("Enter a time to check, exactly in that format [h:mm AM/PM] : ");
  19.         String timeStr = scan.nextLine();
  20.         scan.close();
  21.  
  22.         String timeFormat = "h:mm a";
  23.         try {
  24.             LocalTime timeToCheck = LocalTime.parse(timeStr,
  25.                     DateTimeFormatter.ofPattern(timeFormat, Locale.ROOT));
  26.             int hour = timeToCheck.getHour();
  27.             if (hour >= 3 && hour <= 12) {
  28.                 System.out.println("Now is non-beer time!");
  29.             } else {
  30.                 System.out.println("Now is Beer time!");
  31.             }
  32.         } catch (Exception e) {
  33.             // TODO: handle exception
  34.             System.out.println("Error! - Invalid time!!!");
  35.         }
  36.     }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement