扫描仪需要更多的输入

时间:2016-01-15 21:55:16

标签: java input java.util.scanner

我的一段代码存在问题,该代码旨在验证用户输入是否为整数且介于数字1-6之间。

问题在于,当我添加验证时,扫描程序会在继续之前等待输入三次。如果我不包含验证码,它将正常运行。有什么想法会发生这种情况吗?

int level;
boolean good = false;
double physAct;
System.out.print("On a scale of 1 to 6, how active\ndo you consider yourself?\n1 = lazy, 6 = pro athlete: ");
System.out.flush();
while (!good){
    if (!in.hasNextInt()){
        in.next();
        System.out.print("Sorry, you must enter a whole\nnumber between 1 and 6: ");
    } else if ((in.nextInt() < 0) || (in.nextInt() > 7)){
        in.next();
        System.out.print("Sorry, you must enter a whole\nnumber between 1 and 6: ");
    } else {
        good = true;
    }
}
level = in.nextInt();
switch(level){
    case 1:
    physAct = 1.2;
        break;

此后,开关继续运行,并用于其他一些操作。

2 个答案:

答案 0 :(得分:1)

你的for循环应该读取输入一次并记住它如上所述。否则,每次调用in.nextInt()都会阻塞,直到您输入另一个整数。保持接近相同的代码,您需要执行以下操作。

while (!good){
    if (!in.hasNextInt()){
        in.next();
        System.out.print("Sorry, you must enter a whole\nnumber between 1 and 6: ");
    } else {
        level = in.nextInt();
        if (level < 0 || level > 6) {
            System.out.print("Sorry, you must enter a whole\nnumber between 1 and 6: ");
        } else {
            good = true;
        }
    }
}

在循环后删除level = in.nextInt();,因为您已经在级别中阅读。

答案 1 :(得分:1)

问题是您的测试(in.nextInt() < 0) || (in.nextInt() > 7)都调用nextInt()。你需要调用一次,保存结果并检查它的值。

int value = in.nextInt();
...
...(value < 0) || value > 7)