In the following code from "Java: A Beginner's guide", the for loop seems to iterate more than once when a single character is typed, even though the loop control variable, i, should only be incremented by one each iteration.
The condition to enter the for loop is based on user input. The program will enter the loop and increment i by one until the character S is typed by the user. Every time the program enters the loop, i is printed out.
class ForTest {
public static void main(String args[])
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
for(i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
So it is expected that when a character other than S is typed, the program prints out Pass #0 and then waits for the user to input the next character. Oddly, it loops thrice, printing Pass #0 Pass #1 and Pass #2 before asking for user to input the next character.
Expected:
a
Pass #0
b
Pass #1
S
Actual:
a
Pass #0
Pass #1
Pass #2
b
Pass #3
Pass #4
Pass #5
S