21 What is the difference between the usage of while and do-while loops when learning Java from scratch?

Author : Sun Yuchang, nicknamed [ Brother Yiyi ], and [ Brother Yiyi ] is also me

Senior teaching researcher of Qianfeng Education, CSDN blog expert, Wanfan blogger, Alibaba Cloud expert blogger, high-quality Nuggets author

Supporting project information

https://github.com/SunLtd/LearnJava
https://gitee.com/sunyiyi/LearnJava

foreword

In the last article, Brother Yi explained the concept of loops to everyone, and focused on explaining the use of for loops. But in Java, in addition to the for loop, there are loop forms such as while, do-while, and foreach. Today, Brother Yi will use another article to explain the use of the while loop.

----------------------------------------------- Foreplay is over Finished, the wonderful begins -------------------------------------------- -

The full text is about [ 2000] words, no nonsense, just pure dry goods that allow you to learn techniques and understand principles! This article contains rich cases and videos with pictures, so that you can better understand and use the technical concepts in the article, and can bring you enough enlightening thinking...

1. while loop

1. Basic Grammar

The basic syntax of a while loop is as follows:

while(循环条件){ 
    //循环体 
}

The while loop is a "while" loop structure . When the loop condition is true, the loop body will be executed. If the condition is not met, the loop body will not be executed once. So in the while loop, when the execution reaches a certain level, the loop condition must become false, otherwise it will become an "infinite loop". The infinite loop will cause the CPU to be occupied by 100%, and the user will feel that the computer is running slowly, so we should avoid writing infinite loop code. In addition, if the logic of the loop condition is wrongly written, it may also cause unexpected results.

Everyone should also note that in the while loop, other loops can also be nested!

2. Execution order

According to the basic syntax of the while loop, Yi Ge will sort out its execution sequence for everyone:

  1. If the condition in the while loop is true, execute the loop body;
  2. After the loop body is executed, the loop condition will be judged again...;
  3. The loop ends until the loop condition is false.

3. Code example

Next, we will learn the use of while loop through several cases.

3.1 Case 1

Requirement: Use a while loop to print 100 times "Learn Java with Yiyige"

/**
 * @author 一一哥Sun 
 * QQ:2312119590 
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
public class Demo05 {

	public static void main(String[] args) {
		// while循环
		
		//打印100遍“跟壹壹哥学Java”
		int i = 0;
		while (i < 100) {
			System.out.println("跟壹壹哥学Java"+i);
			//注意要更改i的值,否则条件就用于为真,这就成了死循环了
			i++;
		}
	}

}

3.2 Case 2

Requirement: Use while loop to calculate the cumulative sum of 1-100

/**
 * @author 一一哥Sun 
 * QQ:2312119590 
 * CSDN、掘金、知乎找我哦
​​​​​​​ * 千锋教育
 */
public class Demo05 {

	public static void main(String[] args) {
		// while循环
		
		//计算1~100的和
		int j = 1;
		int sum = 0;
		while(j < 101){            
		    sum = sum + j;
		    j++;
		}
		System.out.println(sum);
	}

}

3.3 Extended case

Requirements: Calculate how many digits a number is?

Implementation idea: If we want to realize this requirement, we can divide the number by 10, and use a number to record the total number of calculations.

/**
 * @author 一一哥Sun 
 * QQ:2312119590 
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
public class Demo06 {

	public static void main(String[] args) {
		// while循环
		
		// 计算一个数是几位数? 实现思路:将该数循环除以10,记录运算了几次
		int num = 12345;
		int temp = num;
		if (num == 0) {
			System.out.println(num + "是1位数");
		} else {
			// 定义一个变量,用于保存循环的次数
			int count = 0;
			while (num != 0) {
				// 将这个数循环除以10
				num = num / 10;
				// 每次循环次数+1
				count++;
			}
			System.out.println(temp + "是" + count + "位数");
		}
	}

}

Two. do-while loop

For a while loop, if the condition is not met, the loop cannot be entered. But sometimes we need to execute at least once even if the condition is not met, then we can consider using a do-while loop. The do...while loop is similar to the while loop, except that the do...while loop is executed at least once.

1. Basic Grammar

The basic syntax of a do-while loop is as follows:

do{ 
   //循环体 
}while(循环条件);

The do-while loop belongs to a " until " loop structure . Because the loop condition is after the loop body, the loop body has been executed once before the loop condition is judged. If the value of the loop condition is true, the loop body will continue to execute until the value of the loop condition is false, then the loop ends.

Attention everyone: In the do-while loop, it is also possible to nest other loops!

2. Execution order

According to the basic syntax of the do-while loop, I will sort out its execution order for you:

  1. First execute the loop body once;
  2. If the condition in the while loop is true, continue to execute the loop body;
  3. When the loop body is executed, the loop condition will be judged again...;
  4. The loop ends until the loop condition is false.

3. Code example

3.1 Case 1

Requirement: Use a do-while loop to print 100 times "Learn programming with Brother Yiyi".

/**
 * @author 一一哥Sun 
 * QQ:2312119590 
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
public class Demo06 {

	public static void main(String[] args) {
		// do-while循环

		// 案例:打印100遍"跟一一哥学编程"
		int i = 1;
		do {
			//循环体至少会执行一次
			System.out.println("跟一一哥学编程"+i);
			//更改i变量的值
			i++;
		} while (i <= 100);
	}

}

3.2 Case 2

Requirements: Students decide whether to continue to code according to the teacher's comments, until the evaluation is ok, and then it is over.

/**
 * @author 一一哥Sun 
 * QQ:2312119590 
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
public class Demo06 {

	public static void main(String[] args) {
		// do-while循环

		//案例:学生根据老师的评语,是否继续敲代码,直到测评结果为ok才结束。
		Scanner sc = new Scanner(System.in);
		String result;
		do{
		    System.out.println("敲代码ing...你看我的代码怎么样???");
		    System.out.println("评价:");   
		    //获取屏幕上输入的文本内容
		    result = sc.next();            
		}while(!result.equals("ok"));
	}

}

------------------------------------------------------​​ ​​​​The feature film is over, here is an afterthought ------------------------------------- ---------

3. Conclusion

So far, Brother Yi has explained the use of the while and do-while loops to everyone. Have you learned it now? So what's the difference between the two?

1. The difference between while and do-while

Here, Brother Yi briefly summarizes the difference between while and do-while loops :

  • Differences in syntax format:

  • The order of execution is different;
  • When the initial loop condition is not satisfied, the while loop will not be executed once; the do-while loop will be executed at least once.

2. Comparison of three cycles

We have now learned all the for, while, and do-while loops. What are the differences between them?

2.1 From the perspective of execution order

  • for, while: judge first, then execute;
  • do-while: execute first, then judge;

2.2 From the perspective of applicable scenarios

  • When the number of loops is determined, the for loop is generally used;
  • When the number of loops is uncertain, a while or do-while loop is generally used.

Brother Yi hopes that everyone can remember the above differences . If you find it difficult to study alone, you can also join Yi Ge 's learning mutual aid group, and everyone can exchange and learn together.

4. Supporting video

If you are not used to reading technical articles, or do not have a good understanding of the technical concepts in the article, you can take a look at the video tutorials selected by Yige for you. The Java learning video accompanying this article is linked as follows:

bilibili html5 player

5. Homework for today

1. The first question

Use a while loop to calculate the factorial result of 10.

2. The second question

Use a do-while loop to print out all integers between 10 and 100 that are divisible by both 5 and 9.

Guess you like

Origin blog.csdn.net/syc000666/article/details/130195502