-3

と を使おうとしていtryますcatch。入力された入力が有効でない場合、ループは繰り返され、ユーザーに再度入力を求めますが、機能していません。何か間違ったことを入力すると、System.out.println.

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 x = 1;
        int month, day, year;

        do {
            try {    
                System.out.println("Please enter a month MM: ");
                month = scan.nextInt();

                if(month>12 && month<1)
                {
                    System.out.println("FLOP");
                } 
                x=2;
            }
            catch(Exception e){
                System.out.println("not today mate");
            }
        }
        while(x==1);             
    }
}
4

3 に答える 3

0

まずあなたの状態が間違っています。

あなたが持っている:

if(month>12 && month<1)
{
  System.out.println("FLOP");
}

したがって、月は 12 より大きく、同時に 1 より小さくすることはできません。

AND の代わりに OR を入れたかったと思います。

if(month > 12 || month < 1)
{
  System.out.println("FLOP");
}

例外として、ユーザーが数値以外を入力したり、入力が疲れた場合に発生する可能性があります。例外: InputMismatchException - 次のトークンが Integer 正規表現と一致しない場合、または範囲外の場合 NoSuchElementException - 入力が使い果たされた場合 IllegalStateException - このスキャナーが閉じられている場合

于 2013-03-22T01:42:35.413 に答える
0

これはあなたの問題に対する有効な解決策です

public static void userInput(){
        Scanner scan = new Scanner(System.in);
        int x = 1;
        int month, day, year;

        System.out.println("Please enter a month MM: ");
        month = scan.nextInt();
        boolean i = true;
        while(i == true)
        {
            if(month < 12 && month > 1)
            {
                System.out.println("FLOP");
                i = false;
            }
            else if(month >= 12 || month <= 1)
            {
                System.out.println("not today mate");
                month = scan.nextInt();                
            }
        }     

  }
于 2013-03-22T01:50:56.973 に答える
0

原則として、例外は例外的な状況で使用され、プログラムのロジックを駆動するためではありません。この場合、入力データの検証は例外的な状況ではありません。ユーザーがエラーを起こし、間違った番号を入力するのは正常な状態です。入力をループに入れて、正しい値が入力されるまで繰り返します (おそらく、ユーザーがキャンセルするオプションを使用して)。

于 2013-03-22T01:23:14.273 に答える