为什么这个java输入验证循环不起作用
试图让程序运行的是,如果用户没有输入“是”或“否”,则用户必须保持在while循环中。将此更改为为什么这个java输入验证循环不起作用,java,Java,试图让程序运行的是,如果用户没有输入“是”或“否”,则用户必须保持在while循环中。将此更改为 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; Scann
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");
}
}
}
这个
因为(first!=“y”| first!=“n”)
总是正确的
如果first=='y'
那么first!='n'
为真
如果first=='n'
那么first!='y'
为真
所以,虽然条件总是正确的
您需要的不是|
,而是&&
[和]
while( first !='y' && first !='n') {
System.out.println("please enter yes or no");
}
将代码替换为:
while( first !='y' || first !='n') is always true.
while(first!=“y”| first!=“n”)
始终为真。
操作如下所示
条件1条件2结果
千真万确
真假假真
假真真
假假假假
在您的情况下,一个条件始终为真,因此它每次都进入while循环
而操作系统的工作原理如下
条件1条件2结果
千真万确
真假假假
假真假
假假假假
因此,不要使用或尝试使用AND
e、 g.
while(first!=“y”&&first!=“n”)
您应该将代码更改为
while( first !='y' && first !='n')
考虑一下while条件在逻辑上总是正确的。while应该包含
input=keyboard.nextLine()代码>。否则,first将永远保持不变。嗯,我想当first不等于y或first不等于n时,逻辑将保持不变,哦,我看到or语句只需要一条语句为true,因此如果有人输入no,那么first将不等于y,因此循环将开始。这可能会帮助您,也可能会让您更加困惑:while(first!='y'&&first!='n')
相当于,而(!(first='y'| | first='n')
我发现后者更具可读性,因为它更像你用英语描述的条件。是的,这是Demorgans逻辑定律
while( first !='y' && first !='n')
boolean b=false;
while(b==false){
if(first !='y' || first !='n'){
System.out.println("please enter yes or no");
} else {
b=true;
}
}