在防止输入错误时使用异常

时间:2013-03-21 22:23:17

标签: java

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

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);  
  }
}

3 个答案:

答案 0 :(得分: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作为日期)

答案 1 :(得分: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) { 
    ... 
}

答案 2 :(得分: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 );