使用扫描仪扫描Java中的输入

时间:2012-08-23 00:20:02

标签: java loops input while-loop java.util.scanner

此代码检查用户输入的内容是否有效。如果它不是数字,它将继续循环,直到它收到一个数字。之后,它将检查该数字是否在边界内或小于界限。它将继续循环,直到收到入站号码。但我的问题是,当我打印选项时,它只显示插入的最后一个数字之后的前一个数字。为什么会那样?

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);
}

1 个答案:

答案 0 :(得分:3)

这是因为input.nextInt()条件中的while消耗整数,所以读取后面的整数。 编辑您还需要合并两个循环,如下所示:

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);