Home > database >  Why the loop iterate 3 times , when each character is entered?
Why the loop iterate 3 times , when each character is entered?

Time:09-03

Here is the code
When run this code each time enter a character , the loop iterate 3 times
Then it ask for another character
Can you please explain why does happen?

class for_loop{

    public static void main(String args[]) throws java.io.IOExecption{
        System.out.println("Enter the character \n");
        for(int i=0; (char)System.in.read()!='S' ; i  )
            System.out.println("Iteration no #" i);
    }
}

CodePudding user response:

Try with Scanner

class for_loop{
    public static void main(String args[]) throws java.io.IOExecption{
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the character \n");

        for(int i=0; input.next().charAt(0) != 'S'; i  ) {
            System.out.println("Iteration no #"   i);
        }
    }
}

CodePudding user response:

When your program runs, if your input is a, it will iterate 2 times. If your input is ab, it will iterate 3 times.

Why is that? The reason is, whenever you hit ENTER key (aka carriage return character), you are also including that ENTER press key as a character.

Try to run your program again, this time, just press ENTER. you will see the it will iterate 1 time.

  • Related