java basics-07 while statement and do...while statement

while statement

The while statement is a conditional judgment loop statement, its loop method is to use a condition to control whether to continue to execute this statement repeatedly

The execution process is shown as

Examples are as follows:

public class Cycle {

	public static void main(String[] args) {
		int a=1;
        int sum=0;
        //当a小于等于10的时候,将a加到sum中
		while(a<=10) {
            sum+=a;
            a++;            
		}
		System.out.println(sum);
		
	}
}

do...while statement

The while statement is also a conditional judgment loop statement, and its loop method also uses a condition to control whether to continue to execute the statement repeatedly

The difference between it and the while statement is that while first judges whether the condition is established, and then executes the statement , while do...while executes the statement first, and then judges whether the condition is established.

The execution flow chart is:

While and do...while this instance is:

package calculate;

public class Cycle {

	public static void main(String[] args) {
		//执行while语句,当a=0时输出
		int a=10;
		while(a==0) {
			System.out.println("a取值为:"+a);
		}
		
		//执行while语句,当b=0时输出
		int b=20;
		do {
			System.out.println("b取值为:"+b);
		}
		while(b==0) ;
	}
}

View the output result as

55

It can be seen that the while statement sequence is not executed once, while do...while is executed once

 

 

Guess you like

Origin blog.csdn.net/dream_18/article/details/115356759