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.
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! =]
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);
}
}
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! =]
Comment