In the following code why does the string inside println method shows twice.What should I do to show the message once per iteration
package practicejava;
public class Query {
public static void main(String[] args) throws java.io.IOException {
System.out.println("Guess a capital letter Character");
while ((char) System.in.read() != 'S') {
System.out.println("wrong.guess again to finish the program");
}
}
}
When a user writes in console characters, to confirm fact that his input is ready to be passed to application he presses enter key. But console doesn't pass only provided characters, it also adds to input stream (System.in) OS dependent line separator character(s) after it. Some OS use
\r
or\n
(those are single characters,\x
is just notation to represent them) others like Windows use\r\n
(two characters) sequence as line separator.Now those additional characters are also read by
System.in.read()
and since they are not equal toS
System.out.println("wrong.guess again to finish the program");
is executed additional time.To avoid such problems instead of working with raw data via
System.in.read()
consider using classes meant to make our life easier likejava.util.Scanner
Its because the first char that you read is the letter you typed, and then there is a second loop where the character is the line return.
For example on my linux machine, if I input "E" and then press enter, the first loop processes the char 69 'E', and then there is a second loop to process the carriage return (char 10).
What you can do is use a
Scanner
to get the user's input:s.next()
will get the input from the user as a string ands.next().charAt(0)
will return the first character in that string.