【问题标题】:Scanning Inputs in Java using Scanner使用 Scanner 扫描 Java 中的输入
【发布时间】:2012-08-18 11:15:19
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    这是因为while 条件中的input.nextInt() 消耗了整数,所以它后面的一个读取下一个。 编辑你还需要组合这两个循环,像这样:

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

    【讨论】:

    • 我试过你的代码。只有当我输入数字 2 次时,才会读取第二个输入
    • @KyelJmD 哦,我明白了 - 你有另一个 nextInt 在那里,请查看修复。
    • 顺便说一句,您也可以检查这个问题吗? stackoverflow.com/questions/12082557/…
    • 我再次尝试了您的代码。但是这次我尝试输入一个字母。它只读取这封信。与while循环一起
    猜你喜欢
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多