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");
}
}
}
试图获取该程序的原因是,如果用户未输入yes或no,则用户必须保留在while循环中。
最佳答案
更改为
while( first !='y' || first !='n') {
System.out.println("please enter yes or no");
}
这个
while( first !='y' && first !='n') {
System.out.println("please enter yes or no");
}
因为
(first !='y' || first !='n')
始终为true。如果
first =='y'
则first !='n'
为true如果
first =='n'
则first !='y'
为true。因此,当条件始终为真时
您需要的不是
||
而是&&
[和]