问题
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");
}
}
}
回答1:
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 to S
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 like java.util.Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Guess a capital letter Character");
String response = sc.nextLine();
while(!response.equals("S")){
System.out.print("incorrect data, please try again: ");
response = sc.nextLine();
}
回答2:
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).
回答3:
What you can do is use a Scanner
to get the user's input:
package practicejava;
import java.util.Scanner;
public class Query {
public static void main(String[] args) throws java.io.IOException {
Scanner s = new Scanner(System.in);
char c;
do {
System.out.println("Guess a capital letter Character");
c = s.next().charAt(0);
if (c != 's') {
System.out.println("Wrong! Guess again to finish the program.");
}
} while(c != 's');
}
}
s.next()
will get the input from the user as a string and s.next().charAt(0)
will return the first character in that string.
来源:https://stackoverflow.com/questions/53793852/why-does-the-string-inside-println-method-show-twice