繁体   English   中英

获取while循环的条件以一次假打印输出

[英]Getting the condition of a while loop to print out once false

我正在网上课程中练习Java语言。 这只是第一个,我遇到了问题,所以我真的很想在我进步之前先了解一下。

问题是这样的:

complete the while loop in the editor so it will print out "I'm learning while loops!". Do this by adding the condition between the parentheses—don't change line 5, or you could get an infinite loop!

代码是:

var understand = true;

while(){
    console.log("I'm learning while loops!");
    understand = false;
}

我尝试将其添加到条件中:

while(understand === 0){

但是我收到这个错误

糟糕,再试一次。 看来您没有将字符串打印到控制台。 检查您的循环语法!

我的状况不对吗? 可以请人详细说明一下,以便我了解这一点的关键基础。 谢谢!

本练习之前的示例:

var coinFace = Math.floor(Math.random() * 2);

while(coinFace === 0){
    console.log("Heads! Flipping again...");
    var coinFace = Math.floor(Math.random() * 2);
}
console.log("Tails! Done flipping.");

编辑---更新:

You may have noticed that when we give a variable the boolean value true, we check that variable directly—we don't bother with ===. For instance,

var bool = true;
while(bool){
    //Do something
}
is the same thing as

var bool = true;
while(bool === true){
    //Do something
}
but the first one is faster to type. Get in the habit of typing exactly as much as you need to, and no more!

If you happen to be using numbers, as we did earlier, you could even do:

到了while(understand === true)

因为该循环将在第一次启动,因为understand已经设置为true。 然后,在触发时,它将understand设置为false-因此,下次尝试触发循环时,条件将失败并且不会继续。 这样,您将执行一个循环,因此仅打印一次。

如果您的代码如下所示

while(true){
    console.log("I'm learning while loops!");
    understand = false;
}

你会得到一个无限循环! 循环将继续进行,因为条件将始终为真。 现在,只要有某种方法可以使条件为假,例如条件中的变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM