5

私は小さなアルゴリズムを作成していますが、これはその一部です。

ユーザーが整数以外の値を入力した場合、メッセージを出力して、ユーザーに再度数値を入力させたい:

boolean wenttocatch;

do 
{
    try 
    {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class 
    } 
    catch (Exception e) 
    {
        wenttocatch=true;
        System.out.println("xx");
    }
} while (wenttocatch==true);

終わりのないループが発生していますが、その理由がわかりません。

ユーザーが整数以外の数値を入力したかどうかを確認するにはどうすればよいですか?
ユーザーが整数以外の数字を入力した場合、ユーザーに再度入力するように求めるにはどうすればよいですか?

更新
例外を印刷しているときに「InputMismatchException」が発生しました。どうすればよいですか?

4

7 に答える 7

5

トライキャッチをする必要はありません。このコードはあなたのためにトリックを行います:

public static void main(String[] args) {
    boolean wenttocatch = false;
    Scanner scan = new Scanner(System.in);
    int number_of_rigons = 0;
    do{
        System.out.print("Enter a number : ");
        if(scan.hasNextInt()){
            number_of_rigons = scan.nextInt();
            wenttocatch = true;
        }else{
            scan.nextLine();
            System.out.println("Enter a valid Integer value");
        }
    }while(!wenttocatch);
}
于 2015-09-15T18:51:04.157 に答える
0

例外が発生するたびにwenttocatchが設定されtrue、プログラムは無限ループに陥ります。例外が発生しない限り、無限ループは発生しません。

于 2015-09-15T18:31:19.020 に答える
0

sc.nextInt() がエラーを引き起こしている場合のロジックはこれです

1) gotocatch が false に設定されている

2) sc.nextInt() がエラーをスローする

3) gotocatch が true に設定されている

4) 繰り返し[GottoCatch が true であるため]

これを解決するには、catch ステートメントで goingocatch=false を設定します

catch (Exception e) {
               wenttocatch=false;
               System.out.println("xx");
            }

ここに表示されている以上のことをしている場合は、カウンターを使用します[数えている場合は、そうでない場合はブール値]。ただし、それ以上のことをしていない限り、上記の最初のことを行います

boolean wenttocatch;
int count = 0;

            do{


             try {
                 wenttocatch=false;
                number_of_rigons=sc.nextInt(); // sc is an object of scanner class 
            } catch (Exception e) {
               count++;
               wenttocatch=true;
               System.out.println("xx");

            }

            }while(wenttocatch==true && count < 1);

回答コメント:

ユーザーが入らなくなるまでintを取得したいと思います。あなたの入力に応じて、それを行う1つの方法はこれです

int number_of_rigons;
while((number_of_rigons = sc.nextInt()) != null){
    //do something
}
于 2015-09-15T18:33:46.523 に答える