By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,790 Members | 1,201 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,790 IT Pros & Developers. It's quick & easy.

Scanner method: hasNext()

P: 94
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.

Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  2.  
  3. public class test_while_with_scanner_method_has_next
  4. {
  5.     public static void main(String[] args)
  6.     {
  7.         Scanner dataReceiver = new Scanner(System.in);
  8.         int sum = 0;
  9.         int value;
  10.  
  11.         while ( dataReceiver.hasNext() )
  12.         {
  13.             System.out.printf("Enter a value: ");
  14.             value = dataReceiver.nextInt();
  15.             sum += value;
  16.         }
  17.  
  18.         System.out.printf("The sum is %d.", sum);
  19.     }
  20. }
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! =]
Apr 17 '13 #1
Share this Question
Share on Google+
1 Reply


Rabbit
Expert Mod 10K+
P: 12,422
Because the nextInt read in the 1.
Apr 18 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.