Reputation: 5
I am very new to this and working through a tutorial but wanted to fancy it up with a while loop so that the program repeats until "K" is entered by the user. Unfortunately, this seems to read the carriage return and line feed when the incorrect char is entered. This means that "WRONG" is output three times instead of once. Is there any way to exclude these so that only the Character is read? Thanks in advance
class Guess{
public static void main(String args[])
throws java.io.IOException {
char ch, answer ='K';
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
ch = (char) System.in.read(); //read a char from the keyboard
while (ch != answer) {
System.out.println("**WRONG**");
System.out.println ("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
ch = (char) System.in.read(); //read a char from the keyboard
if (ch == answer) System.out.println("**Right**");
}
}
}
Upvotes: 0
Views: 241
Reputation: 632
It's just the statments order. Try this
public class Guess {
public static void main(String args[])
throws java.io.IOException {
char ch, answer = 'K';
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
ch = (char) System.in.read(); //read a char from the keyboard
while (ch != answer) {
ch = (char) System.in.read(); //read a char from the keyboard
if (ch == answer) {
System.out.println("**Right**");
break;
}else{
System.out.println("**WRONG**");
}
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
}
}
}
Upvotes: 0
Reputation: 30809
I would recommend using Scanner
and read the line when user hits return as read
considers return as another character, e.g.:
char answer ='K';
Scanner scanner = new Scanner(System.in);
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
String ch = scanner.nextLine(); //read a char from the keyboard
while (ch.length() > 0 && ch.charAt(0) != answer) {
System.out.println("**WRONG**");
System.out.println ("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
ch = scanner.nextLine();//read a char from the keyboard
}
System.out.println("**Right**");
scanner.close();
Upvotes: 1