1

I have the following program:

public class ForTest {
  public static void main(String[] args)
    throws java.io.IOException {

    int i;

    System.out.print("Press S to stop.");

    for (i = 0; (char) System.in.read() != 'S'; i++)
      System.out.println("Pass #" + i);
  }
}

What I am expecting to receive upon executing this program (after entering say 'A', then 'B', then 'C') is the following:

Press S to stop.'A'
Pass # 0
'B'
Pass # 1
'C'
Pass # 2

Instead, I would receive something like this:

Press S to stop.'A'
Pass # 0
Pass # 1
Pass # 2
'B'
Pass # 3
Pass # 4
Pass # 5
etc.

I am having trouble understanding why the body of the for loop is being executed multiple times before read is invoked again. Any help here would be much appreciated, even if it's just a link to the relevant javadoc. Thanks in advance!

  • Are you typing the single quotes into the console? – nickb Jun 14 '17 at 17:11
  • 2
    Each time you press enter it adds OS line separators to standard input (represented here by `System.in`). Since you are seeing two extra characters I am assuming you are using Windows where default line separator is can be represented is `\r` and `\n`. – Pshemo Jun 14 '17 at 17:12
  • 1
    Generally we avoid using `read()`. Instead we use Scanner class and its `nextLine()` `nextInt()` and other methods. – Pshemo Jun 14 '17 at 17:13
  • To elaborate what @Pshemo said: `Scanner s = new Scanner(System.in);` and then don't use a for-loop, but a while-loop for this. Your for-loop doesn't really care what happens to `i`. – bkis Jun 14 '17 at 17:16
  • While it may not be precise duplicate it should give you general idea about what is happening. If you don't think this is duplicate and you wish it to be reopened let me know. – Pshemo Jun 14 '17 at 17:23

0 Answers0