简体   繁体   English

不明白 Java Scanner 对象在这个例子中是如何工作的(hasNextInt,next...?)

[英]Don't understand how Java Scanner object is working in this example (hasNextInt, next...?)

In my program I need to take an input from a user, but it must be an integer.在我的程序中,我需要从用户那里获取输入,但它必须是一个整数。 If the user doesn't input an integer, I need the program to reprompt them to enter an integer, and keep doing so until they enter one.如果用户没有输入整数,我需要程序重新提示他们输入一个整数,并继续这样做直到他们输入一个。 I found an example while loop code snippet online which works perfectly, but I am having problems understanding why and how it works, and I'd really like to understand better:我在网上找到了一个while循环代码片段的例子,它运行得很好,但我在理解它的工作原理和方式时遇到了问题,我真的很想更好地理解:

Scanner reader = new Scanner(System.in);      
int guess=0;             
System.out.println("Guess the number"); 

while (!reader.hasNextInt()) {      //I get that this is a "not have" boolean
    System.out.println("That's not a number. Please enter a valid number");
    reader.next();
}

guess= reader.nextInt();
System.out.println(guess);

My questions are:我的问题是:

  1. Does the !hasNext condition in the while loop actually trigger the scanner object to ask the user for input and then check that input, or does it only check anything that has already been inputted? while 循环中的 !hasNext 条件是否真的触发了扫描仪对象来询问用户输入然后检查该输入,还是只检查已经输入的任何内容?
  2. Why is it necessary to have the reader.next();为什么需要reader.next(); line after the while loop's main statement and what is this doing exactly? while 循环的主语句之后的一行,这到底是做什么的? I know it's necessary as the program doesn't work when I take it out.我知道这是必要的,因为当我取出它时该程序不起作用。 But is it prompting for input?但它是否提示输入? If yes what happens to this input?如果是,这个输入会发生什么?
  3. When guess= reader.nextInt();当guess= reader.nextInt(); runs, why doesn't it re-prompt the user for input at this point?运行,为什么此时不重新提示用户输入?

Sorry that these are probably really basic questions, I'm new to coding and Java and just can't get my head around what's happening internally in this particular example, though have no problem doing other basic stuff with the Scanner.抱歉,这些可能是非常基本的问题,我是编码和 Java 的新手,只是无法理解在这个特定示例中内部发生的事情,尽管使用 Scanner 做其他基本的事情没有问题。

  1. hasNextInt() only checks whether the next input is an integer. hasNextInt()只检查下一个输入是否为整数。 It won't consume any input at all.它根本不会消耗任何输入。 The ! ! is just negate theu outcome of this function.只是否定这个函数的结果。

  2. As hasNextInt() won't consume, then we need to use next() to consumeo the user input to let hasNextInt() to check with user's next input value.由于hasNextInt()不会消费,那么我们需要使用next()来消费用户输入,让hasNextInt()来检查用户的下一个输入值。 As you won't need it at all, then no need to assign it to any variables.由于您根本不需要它,因此无需将其分配给任何变量。

  3. Scanner won't display the prompt at all. Scanner根本不会显示提示。 The prompt is printed by System.out.println() .提示由System.out.println()打印。

    For the line nextInt() , it is used to consume the next user input.对于nextInt() ,它用于消费下一个用户输入。 Since hasNextInt() must be true when it execute this line, there must be one integer input waiting for consumption, so this method can return immediately with that user input.由于hasNextInt()在执行这一行时必须为真,因此必须有一个整数输入等待消费,因此该方法可以立即返回该用户输入。

It's not particularly intuitive, for sure, so don't feel bad for not getting it immediately.当然,它不是特别直观,所以不要因为没有立即获得它而感到难过。

It seems to me that the problem you're having with your understanding is that that methods such as nextInt may or may not prompt for user input, depending if anything is already in the Scanner.在我看来,您在理解上遇到的问题是nextInt等方法可能会或可能不会提示用户输入,这取决于 Scanner 中是否已经存在任何内容。


Here's the sequence of events:这是事件的顺序:

All your code executes until you hit !reader.hasNextInt() .您的所有代码都会执行,直到您点击!reader.hasNextInt() There's no input so it "blocks" (waits) until there is some input from the user.没有输入,所以它“阻塞”(等待),直到有来自用户的输入。

If the user enters 'A', that's not an integer so we enter the body of the while loop.如果用户输入'A',那不是一个整数,所以我们进入while循环的主体。 We then print the error message.然后我们打印错误信息。

Now, hasNextInt doesn't "consume" (process) the user input when it's checking whether or not it's an integer, so we still have that invalid user input of 'A' sitting in our scanner.现在, hasNextInt在检查用户输入是否为整数时不会“消耗”(处理)用户输入,因此我们的扫描仪中仍然存在无效的用户输入“A”。 We call reader.next() to effectively discard that value.我们调用reader.next()来有效地丢弃该值。

Now we're back to !reader.hasNextInt() .现在我们回到!reader.hasNextInt() The scanner is empty once again, so we prompt for user input.扫描仪再次为空,因此我们提示用户输入。 If they enter another non-integer, that process will simply keep repeating.如果他们输入另一个非整数,则该过程将不断重复。

Say this time we do have a valid user input - they've entered the number 2. This passes the check so our while loop ends and we continue along.假设这次我们确实有一个有效的用户输入——他们输入了数字 2。这通过了检查,所以我们的 while 循环结束,我们继续前进。

We've now got some input in our scanner, but we've not consumed it.我们现在已经在我们的扫描仪中获得了一些输入,但我们还没有使用它。 We're sure it's an integer because of the while loop condition.由于 while 循环条件,我们确定它是一个整数。 We can now consume the input with reader.nextInt() and assign it to our variable.我们现在可以使用reader.nextInt()使用输入并将其分配给我们的变量。

 Try it :)
 public static void main(String[] args) {
        int option;
        if(args!=null&&args.length>0){
        option = Integer.parseInt(args[0]);
        }
        else{
        System.out.println("Enter:\n 1 to run x \n 2 to run y \n");
        Scanner keyboard = new Scanner(System.in);
         option = keyboard.nextInt();
        }
        switch (option) {
            case 1:
                xx
                break;
            case 2:
                yy
                break;
            default:
                break;
        }
    }

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

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