简体   繁体   中英

Trouble with Java scanners, printing in while loops

This code takes integers as input until a non-integer is entered. The highest and lowest inputs are then printed. As-is, the code works.

From the inital print statement to first complete iteration of the while loop, why doesn't it print "Enter an integer: " more than once (the first time before the loop and again after in.hasNextInt() returns true)?

import java.util.Scanner;

    public class MaxMinPrinter
    {
        public static void main(String[] args)
        {
            Scanner in = new Scanner(System.in);
            int max = Integer.MIN_VALUE;
            int min = Integer.MAX_VALUE;

            System.out.print("Enter an integer: ");

           while (in.hasNextInt()){
               System.out.print("Enter an integer: ");
               int x = in.nextInt();
               if (x > max){max = x;}
               if (x < min){min = x;}
           }
           System.out.println(max);
           System.out.println(min);

        }
    }

I was under the impression that this code should i) print, then ii) ask for input to enter the while loop, followed by iii) a second print and iv) moving of the scanner's "cursor" to the next token and potentially assigning new max or minimum values. Why doesnt a second print occur on the first iteration? Or am I misunderstanding the usage of the scanner class?

Thanks for your help.

javadoc for hasNextInt():

 * Returns true if the next token in this scanner's input can be
 * interpreted as an int value in the default radix using the
 * {@link #nextInt} method. The scanner does not advance past any input.

So, basically program is waiting for input at hasNextInt(). If you run in debug mode and keep debug point on first line of while loop, you will see it hits the debug point after first input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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