Accepting Only Allowed Time

Ok, so in Java I want to ask the user for some time in a 24-hour format. I managed to use DateFormat and SimpleDateFormat to tell in what format the time is entered, and then interpret it accordingly, throwing an exception if it does not match this format. Here is what I have:

 DateFormat fmt = new SimpleDateFormat("HH:mm"); Scanner keyboard = new Scanner(System.in); try { String input = keyboard.nextLine(); Date theDate = fmt.parse(input); System.out.println(theDate.toString()); } catch (ParseException e) { System.out.println("Incorrect format!"); e.printStackTrace(); } 

If I enter a word, it really throws an exception. However, if I type something like 234234:2342342 , it really goes and does the math to figure out how many days these hours and minutes correspond, and then displays the actual date. For example, this input:

 input: 23423423:232323 output: Fri Jul 29 07:03:00 PDT 4642 

I am wondering if there is a way to treat this as an exception. Therefore, I only want to accept what formatters ask (H 0-23 and m 0-59), and if it does not fall within these boundaries, it throws an exception or has some way of knowing. I would like to know if there is a way to do this within the formatting classes that I use, or if I need to do this using the Scanner class (how?) Or do I write the parsing and checking code myself, Am I approaching this completely wrong? I'm currently just trying to use the features, so if there is a better way, let me know.

Thanks!

+4
source share
1 answer

I figured this out using the DateFormat setLenient method.

 fmt.setLenient(false); 

Now, having typed everything that does not correspond to the format (hour = from 0 to 23 and minute = from 0 to 59), it throws an exception :)

+7
source

Source: https://habr.com/ru/post/1302313/


All Articles