Search code examples
for-loopuser-inputinputstream

for loop iterated unexpectedly


I am a newbie to Java programming and is trying to self-learn the language. I want to create a program that will terminate when a 's' is typed, but what confuse me is my for loop is iterated twice after a letter is entered?

My code:

public class Demo {
    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);
  
            }

    }

My result:

result

How should I solve this problem?


Solution

  • Well it is because when you press the enter key the \n also gets into the inputstream.

    Thus one iteration is for the letter the other for the \n character.

    A Solution would be:

    public class Demo {
        public static void main(String[] args)
            throws java.io.IOException{
    
            int i;
            System.out.println("Press s to stop: ");
            char c = System.in.read();
            for(i = 0;  c != 's'; i++)
                {
                    if(c == '\n') continue;
                    System.out.println("Pass #"+i);
                    c= System.in.read();
                }
    
        }