0

嗨,我试图创建一个让用户输入日期的代码。然后,我将操纵这个日期来计算每天的旅行费用。我正在努力添加异常以防止输入错误。谁能给我一些关于如何做到这一点的提示?我的代码:

import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class Price
{
  public static void main (String [] args)
  {
    userInput();         
  }

  public static void userInput()
  {
    Scanner scan = new Scanner(System.in);

    int month, day, year;

    System.out.println("Please enter a month MM: ");
    month = scan.nextInt();
    System.out.println("Please enter a day DD: ");
    day = scan.nextInt();
    System.out.println("Please enter a year YYYY: ");
    year = scan.nextInt();
    System.out.println("You chose: " + month + " /" + day +  " /" + year);  
  }
}
4

3 回答 3

1

隐藏方法中的异常处理...

public static int inputInteger(Scanner in, String msg, int min, int max) {
  int tries = 0;
  while (tries < maxTries) {
    System.out.println(msg);
    try {
      int result = in.nextInt();
      if (result < min || result > max) {
        System.err.println("Input out of range:" + result);
        continue;
      }
      return result;
    } catch (Exception ex) {
      System.err.println("Problem getting input: "+ ex.getMessage());
    }
  }
  throw new Error("Max Retries reached, giving up");
}

这有点简单,但对于简单的应用程序来说是一个好的开始。相同类型的循环可以让您验证输入(例如,不要将 35 作为日期)

于 2013-03-21T22:30:09.900 回答
0

我将只放置第一个循环,它要求月份,其他的步骤相同,想法相同,请参见:

int month, day, year;
while(true){
    try{
System.out.println("Please enter a month MM: ");
month=scan.nextInt();
if(month>0&&month<=12)
    break;
else System.err.println("Month should be between 1 and 12");
}catch(InputMismatchException ex){
   System.err.println(ex.getMessage());
     }
}
System.out.println("You chose: " + month );
于 2013-03-21T22:36:10.337 回答
0

可能你应该IllegalArgumentException 这样使用:

if (month < 1 || month > 12 || day < 1 || day > 31)
    throw new IllegalArgumentException("Wrong date input");

Exception基类:

if (month < 1 || month > 12 || day < 1 || day > 31)
    throw new Exception("Wrong date input");

此外,您可以创建自己的子类Exception

class WrongDateException extends Exception
{
   //You can store as much exception info as you need
}

然后抓住它

try {
    if (!everythingIsOk)
        throw new WrongDateException();
}
catch (WrongDateException e) { 
    ... 
}
于 2013-03-21T22:34:29.637 回答