I'm working on a program that converts 24 hour time stamps into 12 hour time stamps. I managed to complete the conversion and loop it, but I need to code in an input validation that checks for incorrect inputs. An example of an incorrect input would be: "10:83" or "1):*2". Can someone show me how I can go about this using an Exception method? So far I have this:
public class conversion {
public static void timeChange() throws Exception {
System.out.println("Enter time in 24hr format");
Scanner sc = new Scanner(System.in);
String input1 = sc.nextLine();
DateFormat df = new SimpleDateFormat("HH:mm");
DateFormat df2 = new SimpleDateFormat ("hh:mm a");
Date date = null;
String timeOutput = null;
date = df.parse(input1);
timeOutput = df2.format(date);
System.out.println("in 12 hour format: " + timeOutput);
decision();
}
public static void decision() throws Exception {
System.out.println("Would you like to enter another time?");
Scanner sc2 = new Scanner(System.in);
String userChoice = sc2.nextLine();
while (userChoice.equalsIgnoreCase("Y")) {
timeChange();
}
System.exit(0);
}
public static void main(String[] args) throws Exception {
timeChange();
}
}
Use java.time
the modern Java date and time API for this.
For a slightly lenient validation:
String inputTimeString = "10:83";
try {
LocalTime.parse(inputTimeString);
System.out.println("Valid time string: " + inputTimeString);
} catch (DateTimeParseException | NullPointerException e) {
System.out.println("Invalid time string: " + inputTimeString);
}
This will accept 09:41, 09:41:32 and even 09:41:32.46293846. But not 10:83, not 24:00 (should be 00:00) and not 9:00 (requires 09:00).
For stricter validation use an explicit formatter with the format you require:
DateTimeFormatter strictTimeFormatter = DateTimeFormatter.ofPattern("HH:mm")
.withResolverStyle(ResolverStyle.STRICT);
And pass it to the parse
method:
LocalTime.parse(inputTimeString, strictTimeFormatter);
Now also 09:41:32 gets rejected.
java.time
with my Java version?If using at least Java 6, you can.
For learning to use java.time
, see the Oracle tutorial or find other resoureces on the net.