0

問題の解決策を見つけようとしましたが、実際に機能する解決策が見つかりませんでした。ですから、解決策が何かわからない場合は、回答しないでください。私は本当に具体的な助けが必要です。

問題は、単純なコードを実行すると、番号を選択でき、ループが正常に機能することです。0 を選択しても機能します (実行は終了します) が、文字や文字列を入力すると問題が発生します... 別の値を入力しようとしても、例外が停止せずにループし続けます。

PS。ここではスキャナーを使用する必要があるため、リーダーなどについては書かないでください。この特定の問題を解決する方法だけです。

乾杯、

コードは次のとおりです(メインのみ):

public static void main(String[] args) {
    // TODO code application logic here
    Scanner sc = new Scanner(System.in);
    int dane = -1 ;

     boolean keepLooping;   //if you delete this works the same with same problem
do  
{    
    keepLooping = false;
    try
    {

            System.out.println("Pick a number:");
            dane = sc.nextInt();


    }catch (InputMismatchException e)
      {
          System.out.println("Your exception is: " + e);
          keepLooping = false;
      }  
    System.out.println("Out from exception");

}while ((dane != 0)||(keepLooping == true));   

}
4

3 に答える 3

0

編集済み

このようにしてください

public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        int dane = -1 ;

         boolean keepLooping;   //if you delete this works the same with same problem
    do  
    {    
        keepLooping = false;
        try
        {

                System.out.println("Pick a number:");
                dane = sc.nextInt();


        }catch (InputMismatchException e)
          {
              System.out.println("Your exception is: " + e);
              keepLooping = false;
              dane = sc.nextInt();
          }  
        System.out.println("Out from exception");

    }while ((dane != 0)||(keepLooping == true)&&(dane!=0));   

    }
于 2014-02-20T08:09:39.090 に答える
0

これを試して:

public static void main(String[] args) {
    // TODO code application logic here
    Scanner sc = new Scanner(System.in);
    int dane = -1 ;

     boolean keepLooping = true;   //if you delete this works the same with same problem
while(keepLooping && dane != 0)  
{    

    System.out.println("Pick a number:");
try
{ 

        dane = Integer.parseInt(sc.next());


}catch (NumberFormatException e)
  {
       keepLooping = true;
  }  
System.out.println("Out from exception");

}
于 2014-02-20T08:10:54.557 に答える
0

問題はあなたが言うときです -

デーン = sc.nextInt();

上記の行で、数値以外の入力を与えると、例外入力の不一致がスローされます。この行が何をするのかを理解しましょう。実際には2つのこと -

最初の sc.nextInt() は整数を読み取り、このタスクが正常に完了した場合にのみ、その整数値を変数 dane に割り当てます。しかし、整数の読み取り中に InputMismatchException がスローされるため、割り当ては発生しませんでしたが、デーンはスキャナーが読み取った新しい値ではなく以前の値を持っているため、デーンはまだ 0 に等しくありません。したがって、ループが続行されます。

お役に立てば幸いです。

于 2014-02-20T08:12:46.280 に答える