Reputation: 174
I would compare a char, but it actually doesn't work:
//...
System.out.print("PROCEED? (Y/N):\t");
line = in.nextLine();
ch = line.charAt(0);
while (ch != 'y' || ch != 'n' || ch != 'Y' || ch != 'N'){
System.out.print("NON-VALID INPUT. TYPE Y-N:\t");
line = in.nextLine();
ch = line.charAt(0);
}
//...
On my terminal, as I press y
or n
, the result is:
PROCEED? (Y/N): y
NON-VALID INPUT. TYPE Y-N: y
NON-VALID INPUT. TYPE Y-N: Y
NON-VALID INPUT. TYPE Y-N: n
NON-VALID INPUT. TYPE Y-N: r
NON-VALID INPUT. TYPE Y-N: d
...
Upvotes: 0
Views: 2997
Reputation: 321
The condition is wrong. You have to put the "and" condition (&&), for only enter to that condition if the user type either except ('Y', 'y', 'N', 'n'). The code would be as follows:
System.out.print("PROCEED? (Y/N):\t");
Scanner in = new Scanner(System.in);
String line=in.nextLine();
Character ch=line.charAt(0);
while(ch!='y' && ch!='n' && ch!='Y' && ch!='N'){
System.out.print("NON-VALID INPUT. TYPE Y-N:\t");
line=in.nextLine();
ch=line.charAt(0);
}
Hope this can help you.
Upvotes: 0
Reputation: 393781
Your condition is wrong. It should be :
while(ch!='y' && ch!='n' && ch!='Y' && ch!='N')
since the loop should continue as long as the input character is different than all 4 acceptable inputs.
Upvotes: 5