简体   繁体   English

我的扫描仪两次要求输入

[英]My scanner asks for an input twice

I seem to have this problem a lot, I can't quite seem to understand how to work scanners 我似乎经常遇到这个问题,我似乎不太了解如何使用扫描仪

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

What I want the code to do is ask for a number, and check if the input is a number. 我要代码执行的操作是要求输入一个数字,然后检查输入是否为数字。 My problem is that it asks fro the number twice and I don't know why. 我的问题是它来回询问两次,我不知道为什么。

If this line of code successfully executes: 如果这一行代码成功执行:

int choiceH = choice1.nextInt();

Then the user has entered an int and the parsing succeeded. 然后,用户输入了一个int ,解析成功。 There's no reason to check hasNextInt() again. 没有理由再次检查hasNextInt()

If the user didn't enter an int , then nextInt() will throw an InputMismatchException , and you should simply catch it, and prompt the user again. 如果用户未输入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);

In the line 在行中

Scanner choice1 = new Scanner(System.in);

the buffer will be empty. 缓冲区将为空。 When you reach the line 当你到达那条线

int choiceH = choice1.nextInt();

you enter a number, and you press Enter. 您输入数字,然后按Enter。 After this, the number will be stored in the buffer and be consumed (the buffer will be empty again). 此后,该编号将存储在缓冲区中并被使用(缓冲区将再次为空)。 When you reach the line 当你到达那条线

while (!choice1.hasNextInt())

the program will check if there is an int in the buffer, but at this moment, it will be empty, so hasNextInt will return false . 程序将检查缓冲区中是否有一个int ,但此刻它将为空,因此hasNextInt将返回false So, the condition will be true and the program will ask for an int again. 因此,条件将为true ,程序将再次请求int

How can you solve it? 你怎么解决呢? You can delete the first nextInt : 您可以删除第一个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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM