Java 永远做循环
我在使用这种方法时遇到了问题,我总是坚持“对不起,您必须指定一个深底锅或薄底锅,再试一次:”即使我键入jimmy、harry、Deeppan、thin、thin。。等我输入deeppan或thin之后,我希望字符串存储在变量“size”中并返回 你知道我错过了什么吗Java 永远做循环,java,while-loop,do-while,Java,While Loop,Do While,我在使用这种方法时遇到了问题,我总是坚持“对不起,您必须指定一个深底锅或薄底锅,再试一次:”即使我键入jimmy、harry、Deeppan、thin、thin。。等我输入deeppan或thin之后,我希望字符串存储在变量“size”中并返回 你知道我错过了什么吗 public String Input(){ String size; Scanner sc = new Scanner(System.in); System.out.println("thin or
public String Input(){
String size;
Scanner sc = new Scanner(System.in);
System.out.println("thin or thick: ");
do {
size = scan.next();
if ( !size.equalsIgnoreCase( "thick") || !size.equalsIgnoreCase( "thin" )) {
System.out.print("Sorry you must specify a thick or thin base, try again: ");
} else {
break;
}
} while ( true );
return size;
}
while(true)
将使循环无限,因为它总是true
原因是您正在执行|
操作原因:
!size.equalsIgnoreCase( "Deeppan") || !size.equalsIgnoreCase( "thin" )
尺寸
不能同时为“深盘”和“薄”:
尝试:
ps.“size”不是最好的变量名…在if条件下将| |更改为&&。目前,如果您键入“thin”,条件将为真,因为它不是deeppan,反之亦然 您的
if
中的语句始终为true
你应该使用其中一种
!size.equalsIgnoreCase( "Deeppan") && !size.equalsIgnoreCase( "thin" )
或
它总是正确的,因此永远不会到达
else
示例1:尺寸为“Deeppan”:!尺寸。相等信号箱(“深盘”)|| |!大小相等信号盒(“薄”)
= !没错!假
=假| |真
=正确
示例2:大小为“foo”:
!尺寸。相等信号箱(“深盘”)|| |!大小相等信号盒(“薄”)
= !错!假
=正确| |正确
=true没有理由使用
do while
,请尝试这样,条件检查变得更简单:
while (true) {
size = scan.next();
if (size.equalsIgnoreCase("deeppan") || size.equalsIgnoreCase("thin"))
return size;
System.out.println("Sorry you must specify a Deeppan or Thin base, try again:");
}
尤尔声明
如果(!size.equalsIgnoreCase(“Deeppan”)| |!size.equalsIgnoreCase(“thin”))
这永远是真的 它将一直运行,直到while()不为true,但您将其设置为始终为true。如果条件的计算结果不为true,则他有一个break语句,这应该可以工作。您必须使用调试器并计算if中的两个表达式。在这种情况下,使用括号总是有帮助的,因为它更容易阅读哪个表达式将首先求值…我认为它需要&&
可能?不到24小时前,我们就帮助您解决了这个问题。你已经学会了如何制作一个正确的布尔表达式。是的,就是这样,很好的理解。这可能是你感兴趣的地方
!(size.equalsIgnoreCase( "Deeppan") || size.equalsIgnoreCase( "thin" ))
while (true) {
size = scan.next();
if (size.equalsIgnoreCase("deeppan") || size.equalsIgnoreCase("thin"))
return size;
System.out.println("Sorry you must specify a Deeppan or Thin base, try again:");
}