-2

I was testing some piece of code and came across something interesting on which I would need some expert opinion.

A simple program that stops the loop when the input is s but seems the on each input the loop is iterated twice, i guess that's because of the IO delay. Correct me if I am wrong.

public static void main(String[] args) throws java.io.IOException {
        int i;
        System.out.println("Type s to stop.");
        for(i = 0; ; i++) {
            char value = (char) System.in.read();
            if(value=='s'){
                break;
            }
            System.out.println("Pass # " + i);
        }
    }

output:

enter image description here

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78

1 Answers1

2

When you enter a char a as an input, there are actually two characters which are entered.

  • a
  • \n

But, when you are reading a char, it reads one by one. Hence, it is looped twice.

Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86