简体   繁体   English

While和do While循环

[英]While and do while loops

I'm new to this site and also very new to Java and I'm trying to understand the do while loops 我是这个网站的新手,也是Java的新手,我试图了解do while循环

Question: What is the output and why? 问题:输出是什么,为什么?

public class DoWhile {
    public static void main(String[] args) {
        int i = 1; 

        do { 
            System.out.println("i is : " + i); 
            i++; 
        } while(i < 1);  
    } 
} 

I get that the output is "i is : 1" but I'm trying to understand why. 我得到的输出是“ i is:1”,但我试图理解原因。 It stops once it hits while because i isn't less that 1, right? 一旦击中它就会停止,因为我不小于1,对吗?

Just trying to get my head around it so any help will be appreciated. 只是想尽我所能,任何帮助将不胜感激。

Yes. 是。 Correct. 正确。

do { } while (condition);

This will perform the code at least once, regardless of the condition. 无论条件如何,这将至少执行一次代码。 After the first execution it will check the condition, which will evaluate to false (1 is not smaller than 1) and thus it will stop. 第一次执行后,它将检查条件,条件将被评估为false(1不小于1),因此将停止。

Yes, the output is 是的,输出是

i is : 1

The do-while loop will always execute at least once, because the condition isn't evaluated before the loop is entered; do-while循环将至少执行一次,因为在进入循环之前不会评估条件。 it's only evaluated at the end of each iteration. 仅在每次迭代结束时进行评估。 This is in contrast to the while loop, whose condition is checked before the first iteration as well as after each iteration. 这与while循环相反, while循环的条件是在第一次迭代之前以及每次迭代之后都进行检查。

i is 1 at the start, then print occurs, then i is incremented to 2 . i 1开始是1 ,然后进行打印,然后i增加到2 Then the condition is evaluated -- it's false , so the loop terminates. 然后评估条件-它为false ,因此循环终止。

输出仅为1因为do导致循环至少执行一次,但是while中的条件不会让循环重复执行,因为i永远不会小于1

It is no more 1 不再是1

public class DoWhile {
    public static void main(String[] args) {
        int i = 1; // i is 1

        do { 
            System.out.println("i is : " + i); //still i is 1
            i++; // this makes i = 2;
        } while(i < 1);  
    } 
} 

if you notice the comments it is no more 1 after the first iteration 如果您注意到注释,则在第一次迭代后不再为1

Yes, the output is 1 because in a do-while loop the statements within the do block are always executed at least once. 是的,输出为1,因为在do-while循环中,do块中的语句始终至少执行一次。

After the do block is executed the i value becomes 2 and the while block is not executed. 执行do块后,i值为2,而while块不执行。

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. do-while和while之间的区别在于do-while在循环的底部而不是顶部评估其表达式。 Therefore, the statements within the do block are always executed at least once 因此,do块中的语句始终至少执行一次

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

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