I'm learning Java with the book "Java: A Beginner's Guide". The book shows this example of the for loop:
// Loop until an S is typed
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);
}
}
And the output is:
Press S to stop.
s
Pass #0
Pass #1
Pass #2
d
Pass #3
Pass #4
Pass #5
S
I do not understand why it writes three times Pass # each time I press a different keyboard key to S. I think it should write Pass # only once. Thank you.
You pressed s
and then return. That "return" generated two more characters - \r
and \n
(I assume you're on Windows). Those are then returned by System.in.read()
.
Here's an example which makes that clearer:
class ForTest {
public static void main (String args[]) throws java.io.IOException {
int i;
System.out.println ("Press S to stop.");
char c;
for (i = 0; (c = (char) System.in.read()) != 'S'; i++) {
System.out.println ("Pass #" + i + "; c=" + (int) c);
}
}
}
Output:
Press S to stop.
a
Pass #0; c=97
Pass #1; c=13
Pass #2; c=10
b
Pass #3; c=98
Pass #4; c=13
Pass #5; c=10
S
\r
is Unicode character 13, and \n
is 10.
See more on this question at Stackoverflow