我的扫描仪要求输入两次

时间:2014-06-20 05:03:09

标签: java integer

我似乎有很多这个问题,我似乎无法理解如何使用扫描仪

System.out.println("Please enter a number");
Scanner choice1 = new Scanner(System.in);
int choiceH = choice1.nextInt();

while(!choice1.hasNextInt()){
    System.out.println("Please enter a number");
    choice1.next();
}

我想让代码做的是询问一个数字,并检查输入是否为数字。 我的问题是,它要求两次,我不知道为什么。

2 个答案:

答案 0 :(得分:0)

如果这行代码成功执行:

int choiceH = choice1.nextInt();

然后用户输入了int,解析成功。没有理由再次检查hasNextInt()

如果用户未输入int,则nextInt()会抛出InputMismatchException,您只需抓住它,然后再次提示用户。

boolean succeeded = false;
int choiceH = 0;
Scanner choice1 = new Scanner(System.in);

do {
    try {
        System.out.println("Please enter a number");
        choiceH = choice1.nextInt();
        succeeded = true;
    } 
    catch(InputMismatchException e){
        choice1.next();   // User didn't enter a number; read and discard whatever was entered.
    }
} while(!succeeded);

答案 1 :(得分:0)

在第

Scanner choice1 = new Scanner(System.in);

缓冲区将为空。当你到达

int choiceH = choice1.nextInt();

输入一个数字,然后按Enter键。在此之后,该数字将被存储在缓冲区中并被消耗(缓冲区将再次为空)。当你到达

while (!choice1.hasNextInt())

程序会检查缓冲区中是否有int,但此时它将为空,因此hasNextInt将返回false。因此,条件为true,程序将再次要求int

你如何解决?你可以删除第一个nextInt

System.out.println("Please enter a number");
Scanner choice1 = new Scanner(System.in);
int choiceH = -1; // some default value

while (!choice1.hasNextInt()) {
    System.out.println("Please enter a number");
    choice1.nextInt();
}