我的申请:
System.out.print("Please enter date (and time): ");
myTask.setWhen(
input.nextInt(),
input.nextInt(),
input.nextInt(),
input.nextInt(),
input.nextInt());
我的二传手:
public void setWhen(int year, int month, int date, int hourOfDay, int minute){
this.year = year;
this.month = month;
this.date = date;
this.hourOfDay = hourOfDay;
this.minute = minute;
它准备好让用户输入日期和时间时抛出异常。此外,如果用户进入2013年4月7日下午1:30而不是4,7,2013,13,30,会发生什么? 感谢。
答案 0 :(得分:0)
代码应该是这样的(只是简单的想法):
System.out.print("Please enter date (and time): ");
String inputText;
Scanner scanner = new Scanner(System.in);
inputText = scanner.nextLine();
scanner.close();
//parse input and parsed put as input parameter for your setwhen() method
setWhen(myOwnParserForInputFromConsole(inputText));
答案 1 :(得分:0)
从javadoc,nextInt
抛出“InputMismatchException
- 如果下一个标记与整数正则表达式不匹配,或者超出范围”。这意味着您无法盲目致电nextInt
并希望输入为int
。
您可能应该将输入读作String
并对该输入执行检查,以查看它是否有效。
public static void main(String[] args) throws IOException {
final Scanner scanner = new Scanner(System.in);
//read year
final String yearString = scanner.next();
final int year;
try {
year = Integer.parseInt(yearString);
//example check, pick appropriate bounds
if(year < 2000 || year > 3000) throw new NumberFormatException("Year not in valid range");
} catch (NumberFormatException ex) {
throw new RuntimeException("Failed to parse year.", ex);
}
final String monthString = scanner.next();
final int month;
try {
month = Integer.parseInt(monthString);
//example check, pick appropriate bounds
if(month < 1 || month > 12) throw new NumberFormatException("Month not in valid range");
} catch (NumberFormatException ex) {
throw new RuntimeException("Failed to parse month.", ex);
}
//and the rest of the values
}
然后,当您拥有所有输入且已知它们有效时,请致电setWhen
。
显然,您可以尝试再次阅读该号码,而不是抛出异常。
答案 2 :(得分:0)
使用标准的另一种方式:
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
public class Calend {
public static void main( String[] args ) throws ParseException {
Calendar cal = Calendar.getInstance();
DateFormat formatter =
DateFormat.getDateTimeInstance(
DateFormat.FULL, DateFormat.FULL );
DateFormat scanner;
Date date;
scanner = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT );
date = scanner.parse( "7/4/2013 21:01:05" );
cal.setTime( date );
System.out.println( formatter.format( cal.getTime()));
scanner = DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.MEDIUM );
date = scanner.parse( "7 avr. 2013 21:01:05" );
cal.setTime( date );
System.out.println( formatter.format( cal.getTime()));
scanner = DateFormat.getDateTimeInstance(
DateFormat.FULL, DateFormat.FULL );
date = scanner.parse( "dimanche 7 avril 2013 21 h 01 CEST" );
cal.setTime( date );
System.out.println( scanner.format( cal.getTime()));
}
}
如果你想使用不同的Locale,它在DateFormat中存在一个处理它的构造函数。