Reputation: 71
import java.util.Scanner;
//this program test input validation yes or no program
public class Fool
{
public static void main(String [] args)
{
String input;
char first;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter yes or no ");
input=keyboard.nextLine();
first=input.charAt(0);
System.out.print(first);
while( first !='y' || first !='n')
{
System.out.println("please enter yes or no");
}
}
}
What is trying to get the program to is that the user has to remain in the while loop if the user does not put in yes or no.
Upvotes: 2
Views: 556
Reputation: 395
You should change your code to
boolean b=false;
while(b==false){
if(first !='y' || first !='n'){
System.out.println("please enter yes or no");
} else {
b=true;
}
}
Upvotes: 1
Reputation: 72
while( first !='y' || first !='n')
is always true.
As OR operation works as follows
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
In your case one condition will be always true, therefore it enters in while loop everytime While AND operation works as follows
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
so instead of using OR try using AND
e.g. while( first !='y' && first !='n')
Upvotes: 1
Reputation:
while( first !='y' || first !='n') is always true.
Replace your code with:
while( first !='y' && first !='n')
Upvotes: 1
Reputation: 9872
change this to
while( first !='y' || first !='n') {
System.out.println("please enter yes or no");
}
this
while( first !='y' && first !='n') {
System.out.println("please enter yes or no");
}
because (first !='y' || first !='n')
is always true.
if first =='y'
then first !='n'
is true
if first =='n'
then first !='y'
is true.
so while condition is always true
what you need is not ||
but &&
[and ]
Upvotes: 2