我的应用程序:
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 30,而不是2013年4月7日13 :30,会发生什么情况?谢谢。
发布于 2013-04-08 02:44:56
代码应该是这样的(只是快速的想法):
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));发布于 2013-04-08 02:56:44
在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。
显然,您可以尝试再次读取数字,而不是抛出异常。
发布于 2013-04-08 03:06:39
使用标准的另一种方式:
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()));
}
}如果你想使用不同的语言环境,它在DateFormat中有一个构造函数来处理它。
https://stackoverflow.com/questions/15866205
复制相似问题