soundofsilence
soundofsilence

Reputation: 339

Java Unexpected Output from Scanner

Can anyone tell me why the following produced the output it does?

System.out.print("Enter an integer: ");
int number = in.nextInt();
System.out.println(number);
while(in.hasNextInt())
{
   System.out.print("Enter an integer: ");
   number = in.nextInt();
   System.out.println(number);
}

The output will be something like:

    Enter an integer: 5
    5
    10
    Enter an integer: 10
    16
    Enter an integer: 16
    ...

I understand I can achieve what I want (which is to ask the user for an integer input and print the input) by reversing the print statements... but why is this the case? Any wisdom much appreciated!

Upvotes: 0

Views: 66

Answers (1)

BackSlash
BackSlash

Reputation: 22233

There is why you get that output:

System.out.print("Enter an integer: ");
int number = in.nextInt();   //Waits for user input
System.out.println(number);
while(in.hasNextInt())       //Waits for another user input
{
   System.out.print("Enter an integer: ");
   number = in.nextInt();
   System.out.println(number);
}

Upvotes: 2

Related Questions