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

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 に答える
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 に答える