Java do-while循环不起作用
我希望我的程序继续问这个问题,直到得到它可以使用的响应,特别是从0到20的数字。我在这个类上有很多其他的东西,所以这里有一个小的摘录,其中do-while是(我已经将变量和所有内容命名为一切。
public static void main(String[] args) { do { halp = 1; System.out.println("What level is your fort?"); Scanner sc = new Scanner(System.in); try { fortLevel = Integer.parseInt(sc.nextLine()); } catch(NumberFormatException e){System.out.println("Numbers only, 0-20"); halp = 0; } if(halp 1) { work = true; } while(work = false); }
您在while
表达式中使用了一个赋值:
while(work = false);
你可以替换
while(work == false);
或更好
while(!work);
如果变量halp
和work
在其他任何地方都没有使用,那么它们可以被删除,为您提供:
do { System.out.println("What level is your fort?"); Scanner sc = new Scanner(System.in); try { fortLevel = Integer.parseInt(sc.nextLine()); } catch (NumberFormatException e) { System.out.println("Numbers only, 0-20"); } } while (fortLevel < 0 || fortLevel > 20);
while(work = false); // here you are assigning false to work
应该
while(work == false); //here you are checking if work is equal to false
-
=
用于赋值的赋值运算符 -
==
一个等于运算符,用于检查两个操作数是否具有相同的值。
由于工作是布尔值,你甚至可以使用它:
while(!work)
你也可以这样做:
if(!work) {break;}