的java.util.Calendar
问题描述:
我的应用程序:的java.util.Calendar
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,会发生什么? 谢谢。
答
代码应该是这样的(只是快速的想法):
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));
答
从javadoc,nextInt
抛出“InputMismatchException
- 如果下一个标记不匹配Integer正则表达式,或者超出范围”。这意味着您不能盲目地拨打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
。
显然,你可以,而不是抛出一个异常,再次尝试和读取数字。
答
的另一种方法,通过使用标准:
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的一个构造函数,处理它。
抛出什么异常? – 2013-04-07 18:36:23
您可以添加定义'input'的代码,以便我们可以看到您所做的事情吗? – 2013-04-07 18:38:14
'input'是一个'Scanner',我相信。问题在于比较下午1:30到13:30。 – Aubin 2013-04-07 18:41:39