简体   繁体   English

仅接受有效时间

[英]Accepting only Valid Time

Alright so in Java I want to ask the user for a time in 24-hour format. 好吧,在Java中我想以24小时格式询问用户一段时间。 I have managed to leverage DateFormat and SimpleDateFormat to tell it what format the time is being entered in and then to interpret that accordingly, throwing an exception if it does not follow that format. 我已经设法利用DateFormatSimpleDateFormat来告诉它输入时间的格式,然后相应地解释它,如果它不遵循该格式则抛出异常。 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 type in a word, it indeed throws an exception. 如果我输入一个单词,它确实会引发异常。 However, if I type in something like 234234:2342342 it actually goes and does the math to figure out how many days those hours and minutes equate to, then outputs the actual date. 但是,如果我键入类似234234:2342342它实际上会进行数学计算,以确定这些小时和分钟相等的天数,然后输出实际日期。 For example, given 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. 我想知道是否有办法将此视为例外。 So I want to only accept what the formatters specify (H 0-23 and m 0-59), and if it does not fall within these boundaries, throw an exception or have some way of knowing. 所以我想只接受格式化程序指定的内容(H 0-23和m 0-59),如果它不属于这些边界,则抛出异常或有某种了解方式。 What I would like to know is if there is a way to do this within the formatter classes I am using, or if it should be done using the Scanner class (how?), or if I have to write the parsing and validation code myself. 我想知道的是,如果有一种方法可以在我正在使用的格式化程序类中执行此操作,或者是否应该使用Scanner类(如何完成?),或者如果我必须自己编写解析和验证代码。 Am I approaching this completely wrong? 我接近这个完全错了吗? I am currently just trying out the possibilities, so if there is a better way please let me know. 我目前正在尝试各种可能性,所以如果有更好的方法请告诉我。

Thanks! 谢谢!

I figured it out, using DateFormat 's setLenient method. 我想通了,使用了DateFormatsetLenient方法。

fmt.setLenient(false);

Now typing in anything that doesn't fit the format (hour = 0 to 23 and minute = 0 to 59) it throws an exception :) 现在输入任何不符合格式的东西(小时= 0到23和分钟= 0到59)它会引发异常:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM