Scanner method: hasNext()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stdq
    New Member
    • Apr 2013
    • 94

    Scanner method: hasNext()

    Hi, everyone. I'm new to the forum, and I would to ask you how does the following program works. It uses Scanner method hasNext(), and a sample input/output is shown after the code.

    Code:
    import java.util.Scanner;
    
    public class test_while_with_scanner_method_has_next
    {
        public static void main(String[] args)
        {
            Scanner dataReceiver = new Scanner(System.in);
            int sum = 0;
            int value;
            
            while ( dataReceiver.hasNext() )
            {
                System.out.printf("Enter a value: ");
                value = dataReceiver.nextInt();
                sum += value;
            }
            
            System.out.printf("The sum is %d.", sum);
        }
    }
    Sample input/output at the command prompt, as soon as the program starts with command java test_while_with _scanner_method _has_next:

    1
    Enter a value: 3
    Enter a value: 4
    Enter a value: ^Z
    The sum is 8.


    ^Z is the keystroke combination for indicating end-of-file. How is it possible that the first integer entered, 1, is included in the sum?

    Thanks in advance! =]
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Because the nextInt read in the 1.

    Comment

    Working...