MiniMi2022

Beer Time with Reg Ex

Feb 15th, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. public class BeerTime {
  6.     public static void main(String[] args) {
  7.         Scanner myScan = new Scanner(System.in);
  8.         String time = myScan.nextLine();
  9.         Pattern pattern = Pattern.compile("^(?<Hour>[01]?\\d):(?<Min>\\d{2}) (?<AmPm>[AP]M)$");
  10.         Matcher matcher = pattern.matcher(time);
  11.         String result = "";
  12.         if (!matcher.find()) {
  13.             result = "invalid time";
  14.         } else {
  15.             int hour = Integer.parseInt(matcher.group("Hour"));
  16.             int minutes = Integer.parseInt(matcher.group("Min"));
  17.             String am_pm = matcher.group("AmPm");
  18.             if (hour < 1 || hour > 12 || minutes < 0 || minutes > 59) {
  19.                 result = "invalid time";
  20.             } else if (hour > 0 && hour < 12 && am_pm.equals("PM") ||
  21.                       (hour == 12 || hour > 0 && hour < 3) && am_pm.equals("AM")) {
  22.                 result = "beer time";
  23.             } else {
  24.                 result = "non-beer time";
  25.             }
  26.         }
  27.         System.out.println(result);
  28.     }
  29. }
  30.  
Advertisement
Add Comment
Please, Sign In to add comment