0

指定された範囲(0,20)にあり、であるユーザーから有効な整数を取得するための最良の方法は何ですかint。無効な整数の出力エラーを入力した場合。

私は次のようなことを考えています:

 int choice = -1;
 while(!scanner.hasNextInt() || choice < 0 || choice > 20) {
       System.out.println("Error");
       scanner.next(); //clear the buffer
 }
 choice = scanner.nextInt();

これは正しいですか、それとももっと良い方法がありますか?

4

2 に答える 2

1

あなたはこのようなことをすることができます:

Scanner sc = new Scanner(System.in);
int number;
do {
    System.out.println("Please enter a valid number: ");
    while (!sc.hasNextInt()) {
       System.out.println("Error. Please enter a valid number: ");
       sc.next(); 
    }
    number = sc.nextInt();
} while (!checkChoice(number));

private static boolean checkChoice(int choice){
    if (choice <MIN || choice > MAX) {     //Where MIN = 0 and MAX = 20
        System.out.print("Error. ");
        return false;
    }
    return true;
}

このプログラムは、有効な入力を取得するまで入力を要求し続けます。

プログラムのすべてのステップを理解していることを確認してください。

于 2013-03-03T06:35:39.750 に答える
1

while ループ内のどこで選択を変更しますか? 変更されていない場合、if ブロックのブール条件で使用することは期待できません。

Scanner に int がないことを確認する必要があります。int がある場合、選択肢を取得して個別に確認してください。

擬似コード:

set choice to -1
while choice still -1
  check if scanner has int available
    if so, get next int from scanner and put into temp value
    check temp value in bounds
    if so, set choice else error
  else error message and get next scanner token and discard
done while
于 2013-03-03T06:49:54.413 に答える