-1

I am trying to get a string input from user, in which the input format is "HH:MM am/pm", for example "9:10 am"

The input in which I will later use it for displaying the hours, minutes and the am or pm (in my Time class).

Eventually I will implement a try...except.. for checking the input (for the hours/mins, it must be numeric, between the values of 0-12, and only am/pm can be used). Currently my code works only if user input in HH:MM am/pm (not the space in between) and fails if the input, eg. 9:10pm due to the lack of whitespace.

My question - Can I enforce the input, such that the user has to follow a certain convention? In this case, there must be a space between the time and the am/pm?

In my client class, the code is as follows:

class Client
{
  public static void main(String[] args)
  {
    // I have removed the Scanner input method and use hardcoded values for now
    String input = "9:10 pm";
    String[] inputSplit = input.split(" ");
    System.out.printf("\ntime:\t%s\n", inputSplit[0]);
    System.out.printf("am/pm:\t%s\n", inputSplit[1]);

    String[] time = inputSplit[0].split (":");
    
    int hour = Integer.parseInt (time[0].trim() );
    int min = Integer.parseInt (time[1].trim() );

    System.out.printf("hr:\t\t%d\n", hour);
    System.out.printf("mins:\t%d\n", min);
  }
}
j.hall
  • 61
  • 5

2 Answers2

0

Add tolarance to the time input with replaceAll() and validate format with java.time

Time format validation is done with:

LocalTime.parse(time, DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH));

Time format validation in testbench and context:

public static void main(String[] args) {
    List<String> inputList = Arrays.asList("1:10 pm", "02:10PM", "9:10pm"
            , "   11:10   aM   ", "14:10AM", "10:01");

    DateTimeFormatter df = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
    for (String input : inputList) {
        // We give the input some tolerance regarding space and small letters
        String time = input.trim()
                .replaceAll("[aA][mM]", " AM")
                .replaceAll("[pP][mM]", " PM")
                .replaceAll("\\s+", " ");

        String formattedTime = "";
        try {
            formattedTime = LocalTime.parse(time, df).format(df);
        } catch (DateTimeParseException dtpe) {
            System.out.printf("%nTime '%s' is not valid!%n", input.trim());
        }

        if(!formattedTime.isEmpty()) {
            String[] splitTime = formattedTime.split("[\\s:]");
            String hourAsString = splitTime[0];
            String minAsString = splitTime[1];
            String amPmAsString = splitTime[2];

            System.out.printf("\ntime:\t%s\n", formattedTime);
            System.out.printf("am/pm:\t%s\n", amPmAsString);

            int hour = Integer.parseInt(hourAsString);
            int min = Integer.parseInt(minAsString);

            System.out.printf("hr:\t\t%d\n", hour);
            System.out.printf("mins:\t%d\n", min);
        }
    }
}

Output:

time:   1:10 PM
am/pm:  PM
hr:     1
mins:   10

time:   2:10 PM
am/pm:  PM
hr:     2
mins:   10

time:   9:10 PM
am/pm:  PM
hr:     9
mins:   10

time:   11:10 AM
am/pm:  AM
hr:     11
mins:   10

Time '14:10AM' is not valid!

Time '10:01' is not valid!

Meaning of some of the "Pattern Letters and Symbols":

h   = clock-hour-of-am-pm (1-12)
m   = minute-of-hour
a   = am-pm-of-day

Read more about "Pattern Letters and Symbols" here:

https://docs.oracle.com/javase/10/docs/api/java/time/format/DateTimeFormatter.html#ISO_DATE

DigitShifter
  • 801
  • 5
  • 12
0
public static void main(String[] args)
      {
        // I have removed the Scanner input method and use hardcoded values for now
        String input = "9:10pm";
        String newTime="";
        String ampm= "";
         if(input.contains("am")) {   
        newTime= input.substring(0,input.indexOf("am"));
        ampm=input.substring(input.indexOf("am"));
         }
         else {
        newTime= input.substring(0,input.indexOf("pm"));
        ampm=input.substring(input.indexOf("pm"));
         }
         newTime=newTime.concat(" ").concat(ampm);
         System.out.println(newTime);
         
        String[] inputSplit = newTime.split(" ");
        System.out.printf("\ntime:\t%s\n", inputSplit[0]);
        System.out.printf("am/pm:\t%s\n", inputSplit[1]);

        String[] time = inputSplit[0].split (":");
        
        int hour = Integer.parseInt (time[0].trim() );
        int min = Integer.parseInt (time[1].trim() );

        System.out.printf("hr:\t\t%d\n", hour);
        System.out.printf("mins:\t%d\n", min);
      }