[英]java do while loop keeps repeating and I can't figure out why
So I've attached a debugger, and tried different inputs and I can't seem to figure out why this won't get past the loop. 因此,我已经连接了调试器,并尝试了不同的输入,但我似乎无法弄清为什么它不会通过循环。 When ran I enter "l" or "L", then entry gets set to that, then input is set to the capitalized version and then it repeats. 运行时,我输入“ l”或“ L”,然后将输入设置为该值,然后将输入设置为大写版本,然后重复该操作。
public static char displayMenu(){
char input;
sc.nextLine();//clear junk
do {
System.out.println();
System.out.println("\t\t Enter L to (L)oad ");
String entry = sc.nextLine();
input = entry.toUpperCase().charAt(0);
} while (input != 'L' || input!='M' || input != 'P' || input != 'Q');
input
will only have one value. input
将只有一个值。 That value cannot be both L
and M
. 该值不能同时为L
和M
You need to change the termination condition. 您需要更改终止条件。
Your boolean
||
您的boolean
||
is incorrect. 是不正确的。 If a value is L
it is then not M
, P
or Q
so your loop will continue to iterate. 如果值为L
,则它不是M
, P
或Q
因此您的循环将继续迭代。 I think you wanted something like, 我想你想要类似的东西,
while (input != 'L' && input != 'M' && input != 'P' && input != 'Q');
or 要么
while (!(input == 'L' || input == 'M' || input == 'P' || input == 'Q'));
consider when input
is L
, clearly L
is not M
and so your initial while
condition would continue to iterate. 考虑何时input
为L
,显然L
不是M
,因此您的初始while
条件将继续迭代。
您已经使用了逻辑或条件,即使您输入'L',它也只需要运行一个真实的语句,这时您的一个语句为假,而其他语句变为真,因此它会重复。
Like 喜欢
public static void main(String[] args) {
char input;
Scanner sc = new Scanner(System.in);
input = sc.nextLine().charAt(0);//clear junk
do {
System.out.println();
System.out.println("\t\t Enter L to (L)oad ");
String entry = sc.nextLine();
input = entry.toUpperCase().charAt(0);
} while (input != 'L' && input!='M' && input != 'P' && input != 'Q');
}
public static char displayMenu(){
char input;
sc.nextLine();//clear junk
do {
System.out.println();
System.out.println("\t\t Enter L to (L)oad ");
String entry = sc.nextLine();
input = entry.toUpperCase().charAt(0);
} while ((input != 'L') && (input!='M') && (input != 'P') && (input != 'Q'));
try this 尝试这个
De Morgan's laws tell us that 德摩根的法律告诉我们
(input != 'L' || input!='M' || input != 'P' || input != 'Q')
is the same as 是相同的
! (input == 'L' && input=='M' && input == 'P' && input == 'Q')
which must always be true because 这必须始终是真实的,因为
(input == 'L' && input=='M' && input == 'P' && input == 'Q')
must always be false because 必须始终为假,因为
input
can only be equal to one thing at a time. input
一次只能等于一件事。
Use De Morgan's laws to avoid extra NOT's when you can. 尽可能使用De Morgan的定律来避免多余的NOT。 Computers don't care but humans don't process NOT's very well. 电脑不在乎,但人类没有很好地处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.