0

Okay, i'm a beginner learning from "Java Beginner Guide" Book from Herbert Schildt. Here is piece of code i run across when learning for loop chapter.

the code basicly ask for user input and if the user input match with condition which is "s" the loop wont start, if its match its star and print "pass# + i" each time its iterates.

my question is why when i input anything except "s" the output is two line of "pass#"? why not just one line?

    System.out.println("pls type s");

    for( i = 0; (char) System.in.read() != 's'; i++)
        System.out.println("pass#" + i);
t Herm
  • 1
  • 1

2 Answers2

1

It's due to pressing enter after an input, which signals the shell to put your input, which includes the enter press, into standard input. Enter itself has an ASCII value. So, it (enter) is also counted as a character.

Try pressing enter only; you will see a pass# message.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
Shakib Uz-Zaman
  • 581
  • 6
  • 17
0

The System.in.read() function reads data byte wise. So,when you type a character and press enter....what happens is,

Prompt:pls type s

Input:a(press enter)

Java perceives this as: "a \n" as enter is also accounted as a byte value.

As a result of two bytes the print statement is run two times.

Pranay Reddy
  • 113
  • 5