In this program, the loop control variable only increases by 1 every iteration but the output shows otherwise

Viewed 799

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
2 Answers

If you change a little the program in order to debug it:

char myChar;

for(i = 0; (myChar = (char) System.in.read()) != 'S'; i++)
    System.out.println("Pass #" + i + " the character from the console is: " + (byte)myChar);
}

and then run it, you will see what characters are actually comming from the input stream:

Press S to stop.
Pass #0 the character from the console is: 97
Pass #1 the character from the console is: 10
Pass #2 the character from the console is: 98
Pass #3 the character from the console is: 10

97 - is a
10 - is line feed
98 - is b
10 - is line feed


I hope it is clear now to you - if you press a + Enter, then the console returns a + line feed characters to the program, that is two characters, not one.

in for loop it cheaks the condition first and if it is true then it executes the further code i recommend you to use do while loop because it executes the code first and then it cheaks the code

Related