2

「エラー: 0 から 5 までの数字を入力する必要があります」というメッセージを出力し、ユーザーが再度入力できるようにするにはどうすればよいですか?

 int number;
 do 
  {
     String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
     number = Integer.parseInt(textinput);
  } while (!(number >= 0 && number <= 5));
4

8 に答える 8

3

元のコードを最小限に変更する最も簡単な方法は次のとおりです。

int number;
do {
    String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
    number = Integer.parseInt(textinput);
    if((number < 0) || (number > 5) {
        //show error message
        continue;  //continue isn't absolutely necessary here, but perhaps for readability
    }
} while (!(number >= 0 && number <= 5));

これは少し不格好で冗長だと思いますが、基本的に同じ条件を2回チェックしています。次のような方法を使用します。

int number;
String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
while(true) {
    number = Integer.parseInt(textinput);
    if((number >= 0 && number <= 5)) {
        //show error message and prompt for another input
        contine; //As with before, continue isn't necessary here, but could add readability
    } else /*input was good*/ { break; /*exit while loop*/ }
}
于 2013-10-28T13:25:00.447 に答える
1
    String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
    int number = Integer.parseInt(textinput);

    while (!(number >= 0 && number <= 5)) {
        textinput = JOptionPane.showInputDialog("Your number must be between 0 and 5!");
        number = Integer.parseInt(textinput);
    }

    // do stuff
于 2013-10-28T13:27:34.860 に答える
0
        int number;
        if(nummber>0 && number<5)
        {
         do 
          {
             String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
             number = Integer.parseInt(textinput);
          } while (!(number >= 0 && number <= 5));
        }
    else
    {
    System.out.println("you have to enter a number between 0 to 5");
}
于 2013-10-28T13:23:27.673 に答える
0

それはそれと同じくらい簡単でなければなりません。

int number;
do 
{
 String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
 number = Integer.parseInt(textinput);
 if(!(number >= 0 && number <= 5))
     {
       System.out.println("Error: you have to enter a number between 0 and 5");
     }
} while (!(number >= 0 && number <= 5));
于 2013-10-28T13:28:01.387 に答える
-1

このような:

int number;
     do 
      {
         String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
         number = Integer.parseInt(textinput);
         if ( number > 5 || number  < 0)
         {
             System.out.println("Please enter number between 0 to 5");
             return;
         }
          } while (!(number >= 0 && number <= 5));
}
于 2013-10-28T13:27:16.800 に答える