3

このコードは、ユーザーの入力が有効かどうかをチェックします。数値でない場合は、数値を受け取るまでループし続けます。その後、その数値が境界内にあるか、境界未満であるかを確認します。インバウンド番号を受信するまでループし続けます。しかし、ここでの問題は、選択肢を印刷すると、最後に挿入された番号の後の前の番号のみが表示されることです。なぜそうなのですか?

public void askForDifficulty(){
    System.out.println("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: ");
    int choice = 0;
    boolean notValid = true;
    boolean notInbound = true;
    do{
        while(!input.hasNextInt()){
            System.out.println("Numbers Only!");
            System.out.print("Try again: ");
            input.nextLine();
        }
            notValid = false;
            choice = input.nextInt();
    }while(notValid);

    do{
        while(input.nextInt() > diff.length){
            System.out.println("Out of bounds");
            input.nextLine();
        }
        choice = input.nextInt();
        notInbound = false;
    }while(notInbound);

    System.out.println(choice);
}
4

1 に答える 1

3

これはinput.nextInt()、条件内でwhile整数が消費されるため、次の条件が読み取られるためです。EDIT次のように、2 つのループを結合する必要もあります。

int choice = 0;
for (;;) {
    while(!input.hasNextInt()) {
        System.out.println("Numbers Only!");
        System.out.print("Try again: ");
        input.nextLine();
    }
    choice = input.nextInt();
    if (choice <= diff.length) break;
    System.out.println("Out of bounds");
}
System.out.println(choice);
于 2012-08-23T00:24:51.690 に答える