Reputation: 1809
This is my code...
class info{
public static void main (String[]args) throws IOException{
char gen;
while(true) { //problem occurs with this while
System.out.print("\nENTER YOUR GENDER (M/F) : ");
gen=(char)System.in.read();
if(gen=='M' || gen=='F' || gen=='m' || gen=='f'){
break;
}
}
System.out.println("\nGENDER = "+gen);
}
}
This is my output...
ENTER YOUR GENDER (M/F) : h
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) :
ENTER YOUR GENDER (M/F) : m
GENDER = m
Could someone please help me understand why it is asking for the gender so many times.
Upvotes: 0
Views: 125
Reputation: 33534
Use Scanner scan = new Scanner(System.in)
Here is the working version of your code....
public class Info{
public static void main (String[]args) throws IOException{
char gen;
Scanner scan = new Scanner(System.in); // Change made here
while(true) {
System.out.print("\nENTER YOUR GENDER (M/F) : ");
gen= scan.next().charAt(0); // Change made here
if(gen=='M' || gen=='F' || gen=='m' || gen=='f'){
break;
}
else{ // Change made here
System.out.println();
System.out.println("Your Option is not Available, pls try again");
continue;
}
}
System.out.println("\nGENDER = "+gen);
}
}
Upvotes: 0
Reputation: 9206
You are probably workin' on Windows. When you give an answer and hit enter it adds two extra characters '\r'
and '\n'
. From stdin
you receive only one character but those extra two remain in the buffer. When you give an incorrect answer you loop and automatically read from the buffer those two characters. They don't match the gender so the loop continues. The best solution would be to analyze strings instead of characters:
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String s = in.readLine();
Remember to use equals
method instead of ==
in string comparison.
Upvotes: 5
Reputation: 1500675
You pressed return after pressing h
; you won't see the 'h'
until you do so, but then you'll still see the return (and by the looks of it, that's coming out as two characters, possibly '\r'
and '\n'
) before you see the next character.
You may want to read a line of text at a time, instead of a single character - you'll only see the input when the user presses return anyway, and it means you don't need to worry about this particular aspect.
You could use Scanner
for this, or a BufferedReader
wrapping System.in
.
Upvotes: 4