I just started learning coding (Java) for days and I found this problem.
It is a very simple for loops program where the loops will stop executed after the user input an 'S' on the keyboard. It works fine, but if I put the wrong input the loops executed 3 times instead of just once.
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);
}
}
When I put the wrong input, the output should be:
Pass #0
But the actual output are:
Pass #0
Pass #1
Pass #2
Also if I put the wrong input more than one character, it always gives 2 extra output. Let's just say I put an input ABC (3 character). The output will be:
Pass #0
Pass #1
Pass #2
Pass #3
Pass #4
Is the problem are on the code? Can anyone explain why and share the solution?
Note: I tried to run the code on Command Prompt and Eclipse. Both have the same output.
TY,