The latest Java basic series of courses--Day03-Java program flow control

Author Homepage: Programming Compass

About the author: High-quality creator in the Java field, CSDN blog expert
, CSDN content partner, invited author of Nuggets, Alibaba Cloud blog expert, 51CTO invited author, many years of architect design experience, resident lecturer of Tencent classroom

Main content: Java project, Python project, front-end project, artificial intelligence and big data, resume template, learning materials, interview question bank, technical mutual assistance

Favorites, likes, don't get lost, it's good to follow the author

Get the source code at the end of the article

Chapter 2 - Program Flow Control

【Teaching content】

2-1 Statements and Compound Statements

2-2 Sequential structure

2-3 branch structure

2-4 loop structure

2-5 Jump statement in loop

2-6 Recursive algorithm

[ Key points and difficulties ] The key points are the understanding of branch structure and loop structure. The difficulty is the recursive algorithm.

【Ability Requirements】 (1) Master the grammar of branch structure and loop structure (2) Master the knowledge of recursive algorithm

Dear students, today we learn a brand new knowledge - program flow control. What is process control? To put it bluntly, it is to control the execution order of the program.

Let me introduce to the students first, what flow control does the program have, and what solutions does Java provide to control the execution order of the program?

Program flow control is generally divided into three types: sequential structure, branch structure, loop structure

  • Sequential structure: without any control, the code starts from the main method and executes from top to bottom

  • Branch structure: It is to judge whether it is true or false according to the condition, and which codes are selectively executed. In the Java language, two formats are provided, if and switch

  • Loop structure: It is to control the repeated execution of a certain piece of code. Three formats are provided in the Java language, for, while, do-while

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-sbN2Y9kl-1689742908620)(assets/1661129154598.png)]

The above is the main course content we are going to study today

1. Simple and compound sentences

A statement in the Java language can be a simple statement ending with a semicolon ";", or a compound statement enclosed in a pair of curly braces "{}".

复合语句:由多个简单语句构成的语句块

Example:

public static void main(String[] args)
{
    
    
  int a = 10;//简单语句
  ……
   {
    
      //复合语句
     int b;
     int a;  //错误,因变量a前面已定义
    ……
    }
 }

The compound statement of the Java language is different from the C++ compound statement in that the Java language does not allow two variables with the same name to be declared in two nested compound statements.

2. Branch structure

2.1 if branch

Dear students, next we learn the first form of branch structure - if branch.

The function of if is to judge the condition. The result of the judgment can only have two values ​​true or false, and then decide to execute that piece of code according to the result of the condition judgment.

1. What are the application scenarios of the if branch?

For example, in public places such as train stations and subway stations, the body temperature of passing passengers will be taken. If the body temperature is within 37 degrees, it is normal; if the body temperature is above 37 degrees, the device for measuring body temperature will alarm.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-VVCUoY9V-1689742908624)(assets/1661130193692.png)]

For another example, when you use WeChat to pay, the internal program of WeChat will first judge whether your balance is sufficient, and if it is sufficient, the payment can be successful; if the balance is insufficient, it will prompt that the payment failed.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-hxJMhTWW-1689742908625)(assets/1661133550463.png)]

2. Format of if branch

Next, let's take a look at what the if branch looks like in the Java language? There are three formats of if branch in Java.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-7XH0ICIB-1689742908626)(assets/1661131177976.png)]

Next, we will use some actual cases to demonstrate the application of the if statement and the execution flow of each if statement.

3. The first form of if

The code format and execution flow of the first form of if are shown in the figure below

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-vjiPWShi-1689742908628)(assets/1661131910804.png)]

if 第一种形式执行流程如下:
    如果 条件表达式 为true,就执行下面的语句体
    如果 条件表达式 为false,就不执行
// 需求:测量用户体温,发现体温高于37度就报警。
double t = 36.9;
if(t > 37){
    
    
    System.out.println("这个人的温度异常,把他赶紧带走~~");
}

4. The second form of if

The code format and execution flow of the second form of if are shown in the figure below

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-BQRwsnep-1689742908630)(assets/1661132063147.png)]

if 第二种形式执行流程如下:
    如果 条件表达式 为true,就执行下面的语句体1
    如果 条件表达式 为false,就执行else下面的语句体2
// 需求2:发红包,你的钱包余额是99元,现在要发出90元
// 如果钱够触发发红包的动作,如果钱不够,则提示:余额不足。
double money = 19;
if(money >= 90){
    
    
    System.out.println("发红包成功了~");
}else {
    
    
    System.out.println("余额不足~~");
}

5. The third form of if

The code format and execution flow of the third form of if are shown in the figure below

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-8kSGjAQ7-1689742908632)(assets/1661132132708.png)]

if 第三种形式执行流程如下:
    如果 条件表达式1true,就执行下面的代码1; 
    如果 条件表达式1false,就继续判断条件表达式2;

    如果 条件表达式2true,就执行下面的语句体;
    如果 条件表达式2false,就继续判断条件语句体3;

    如果 条件表达式3true,就执行下面的语句体3
    如果 条件表达式3false,就继续判断后面的表达式;

    ....
    如果前面所有条件表达式判断都为false,就执行最后的else语句中的代码
// 需求3:某个公司有一个绩效系统,根据员工的打分输出对应的绩效级别。[0,60) D  [60,80) C [80,90) B [90,100] A
int score = 298;
if(score >= 0 && score < 60) {
    
    
    System.out.println("您的绩效级别是: D");
}else if(score >= 60 && score < 80){
    
    
    System.out.println("您的绩效级别是: C");
}else if(score >= 80 && score < 90){
    
    
    System.out.println("您的绩效级别是: B");
}else if(score >= 90 && score <= 100){
    
    
    System.out.println("您的绩效级别是: A");
}else {
    
    
    System.out.println("您录入的分数有毛病~~");
}

6. Several common problems in using if

When students write if code for the first time, they often have some problems accidentally. Let me show you the problems that students may have, so that you can avoid these problems in the future.

  • The first question: if () cannot be followed by a semicolon ;, otherwise the statement below if has nothing to do with if

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-AXOPYkY0-1689742908633)(assets/1661132888600.png)]

  • The second question: the braces after if, if there is only one line of code, the braces can be omitted

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-9ZloOq69-1689742908635)(assets/1661132851560.png)]

7. if branch summary

We have finished talking about several formats of if branch structure, the execution process of various formats, and the scenarios in which if is used. Let's summarize

  • What does the if branch do? What are some application scenarios?
- if作用:if分支可以根据条件,选择执行某段程序
- if应用场景
    比如1:测量用户体温,发现体温高于37度就报警
    比如2:发红包,你的钱包余额是99元,现在要发出90元
    比如3:根据员工的绩效打分输出对应的绩效级别
  • There are several formats of the if branch, and what is the execution process like?

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-R7P9tb03-1689742908636)(assets/1661133510341.png)]


2.2 switch branch

After learning the if branch, let's learn the second form of the branch structure - the switch branch.

1. The execution flow of the switch branch

The role of the switch branch is to determine which branch code to execute by comparing values . First look at the format and execution process of the switch branch

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Ftx60Bd5-1689742908638)(assets/1661134120042.png)]

Let's demonstrate through a case

/*
需求:做个电子备忘录,在控制台分别输出周一到周五的工作安排
    周一:埋头苦干,解决bug              
    周二:	请求大牛程序员帮忙             
    周三:今晚啤酒、龙虾、小烧烤      
    周四:主动帮助新来的女程序解决bug
    周五:今晚吃鸡
    周六:与王婆介绍的小芳相亲
    周日:郁郁寡欢、准备上班。
*/
String week = "周三";
switch (week){
    
    
    case "周一":
        System.out.println("埋头苦干,解决bug");
        break;
    case "周二":
        System.out.println("请求大牛程序员帮忙");
        break;
    case "周三":
        System.out.println("今晚啤酒、龙虾、小烧烤");
        break;
    case "周四":
        System.out.println("主动帮助新来的女程序解决bug");
        break;
    case "周五":
        System.out.println("今晚吃鸡");
        break;
    case "周六":
        System.out.println("与王婆介绍的小芳相亲");
        break;
    case "周日":
        System.out.println("郁郁寡欢、准备上班");
        break;
    default:
        System.out.println("您输入的星期信息不存在~~~");
}

2. How to choose if and switch

After learning the switch branch, some students may think, there is already an if branch, why is there a switch branch? I feel that the above case can also be done with the if branch? So how do we choose in specific application scenarios?

In terms of function alone, the function of the if branch is more powerful, and the if branch can do everything that the switch branch can do. But which branch form to use specifically, there are also some principles of use

- 如果是对一个范围进行判断,建议使用if分支结构
- 如果是与一个一个的值比较的时候,建议使用switch分支结构

2.3 Precautions for switches

Dear students, let's learn the precautions of swtich next. After the students master these precautions, they can avoid getting into the pit, and they can also deal with some written interview questions.

- 1.表达式类型只能是byteshortintchar
	JDK5开始支持枚举,JDK7开始支持String
	不支持doublefloatdouble
    
- 2.case给出的值不允许重复,且只能是字面量,不能是变量。
		
- 3.正常使用switch的时候,不要忘记写break,否则会出现穿透现象。

1. Demonstrate the data types matched by the switch statement

Dear students, as shown in the figure below, you can use the variables a and b to match in the switch statement. If you encounter an unsupported writing method, IDEA will report an error.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-zvezWL4i-1689742908640)(assets/1661135813464.png)]

2. The value behind the demonstration case can only be a literal value and not a variable

Dear students, you can also try it yourself. The position pointed by the arrow in the figure below can only write literal values, and cannot write variables.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-dOlxYKns-1689742908641)(assets/1661136001680.png)]

3. Demonstrate case penetration phenomenon

When no break is encountered in the switch statement, it will directly penetrate to the next case statement until a break is encountered.

This grammatical design also has its usefulness. When multiple case statements want to execute the same piece of code, you can use the case penetration phenomenon to improve code reusability.

For example: In our program below, we want to ask big programmers to write codes on Tuesday, Wednesday, and Thursday.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-98vrbuet-1689742908642)(assets/1661136414587.png)]

3. Cycle structure

Dear students, next we will study the loop structure. The loop structure can control the repeated execution of a piece of code. Loop structures include for loop, while loop, and do-while loop.

3.1 for loop - format and flow

Here we first learn the for loop. Students focus on mastering the writing format of the for loop and understanding the execution process of the for loop.

1. The format and flow of the for loop

In order to let everyone understand the execution process of the for loop more intuitively, let's look directly at the specific case code.

For example: we want to print out 3 HelloWorld on the console

//需求:打印3行Hello World
for(int i = 0; i < 3; i++) {
    
    
    System.out.println("Hello World");
}

As shown in the figure below, it is executed in the following order of ① ② ③ ④, ② ③ ④…;

When the ② condition is true, then execute the ③④ code in sequence, and then return to ② to continue the judgment

When the ② condition is false, the loop ends

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-HcTYF3Jb-1689742908644)(assets/1661137599188.png)]

Each step of the specific implementation can be seen in the diagram below

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-tsSflNtm-1689742908645)(assets/1661138616082.png)]

Through the above case demonstration, we finally summarize the format of the for loop

//for循环格式:
for (初始化语句; 循环条件; 迭代语句) {
    
    
    循环体语句(重复执行的代码);
}

初始化语句:一般是定义一个变量,并给初始值
循环条件:一般是一个关系表达式,结果必须是true或者false
迭代语句:用于对条件进行控制,一般是自增或者自减
循环语句体:需要重复执行的代码

2. What are the application scenarios of the for loop

Through the above study, we already know how to write the for loop, and also know its execution process.

So in which actual scenarios is it used? In fact, as long as it is repeated, you can use loop statements to do it.

For example: to display the information of 100 mobile phones on JD.com's webpage, we only need to write a copy of the code to display the data and execute it repeatedly.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-seAKXC3B-1689742908646)(assets/1661139301013.png)]

3.2 for loop case 1 - summation

After learning the format and process of the for loop, let's consolidate it through a case. Through this case, the main purpose is to let the students master the idea of ​​using a program to sum.

//1.掌握使用for循环批量产生数据。
for (int i = 1; i <= 100; i++) {
    
    
    System.out.println(i);
}
求和的思路分析:
	1)首先需要定义一个求和变量,一般命名为sum
	2)再遍历得到所有需要求和的数据(1~100之间的所有整数)
	3)让需要求和的数据和sum累加,
	结果:所有数据累加完之后最终sum就是所有数据的和
//2.需求:求1~100中所有整数的和
int sum = 0;
//定义一个循环,先产生1-100,这100个数
for (int i = 1; i <= 100; i++) {
    
    
    //每产生一个数据,就把这个数和sum累加
    sum += i; //sum = sum  + i;
}
System.out.println("1-100的数据和:" +  sum);

Analyze the execution process of the above code:

i=1时:sum=0+1; sum=1;
i=2时:sum=1+2; sum=3;
i=3时:sum=3+3; sum=6;
i=4时:sum=6+4; sum=10;
...
i=100: sum+=99; sum=5050

3.2 for loop case 2 - find odd sum

Requirements: Find the sum of odd numbers between 1 and 100

1. Code writing method 1

求奇数和的思路(只是求和的数据变成了奇数,思路和前面没有变化)
	1)首先需要定义一个求和变量,这里命名为sum1
	2)再遍历得到所有需要求和的数据(1~100之间的所有奇数)
	3)让需要求和的数据和sum1累加,
	结果:所有数据累加完之后最终sum1就是所有数据的和
//1)定义一个变量用于求和
int sum1 = 0;
//2)定义一个循环产生1-100之间的奇数
for (int i = 1; i < 100; i+=2) {
    
    
    // i = 1 3 5 7 ...
    //3)让需要求和的数据和sum1累加,
    sum1 += i;
}
System.out.println("1-100之间的奇数和:" +  sum1);

Execution flow analysis of the above code

初始化sum1=0;

当i=1时:sum1+=1; sum1=1;
当i=3时:sum1+=3; sum1=4;
当i=5时:sum1+=5; sum1=9;
...
当i=99时:sum1+=99; sum1=2500

2. Code writing method 2

求奇数和的思路(只是求和的数据变成了奇数,思路和前面没有变化)
	1)首先需要定义一个求和变量,这里命名为sum2
	2)再遍历得到所有需要求和的数据(1~100之间的所有整数)
	3)在求和之前先对数据判断,如果是奇数,才和sum1累加;否则什么也不干
	结果:所有数据累加完之后最终sum1就是所有数据的和
//1)首先需要定义一个求和变量,这里命名为sum2
int sum2 = 0; 
//2)再遍历得到所有需要求和的数据(1~100之间的所有整数)
for (int i = 1; i <= 100; i++) {
    
    
    //i = 1 2 3 4 5 6 ... 99 100
    //3)在求和之前先对数据判断,如果是奇数,才和sum1累加;否则什么也不干
    if(i % 2 == 1){
    
    
        // i = 1 3 5 7 9 ... 99
        sum2 += i;
    }
}
System.out.println("1-100之间的奇数和:" + sum2);

for loop summary

Regarding the for loop today, it is enough for us to study these few cases, and the key point is to master the execution process of the for loop. In the future, we will often use the for loop, and you will become more and more familiar with it if you use it more. However, in specific scenarios, specific analysis of specific issues is still required.


3.3 while loop - format and flow

Dear students, next we will learn the second loop structure - while loop.

Let's first understand what the while loop looks like, and then write a basic case of the while loop according to the format

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-4fU2qflr-1689742908659)(assets/1661141338265.png)]

// 需求:打印5行Hello World
int i = 0;
while (i < 5) {
    
    
    // i = 0 1 2 3 4
    System.out.println("Hello World");
    i++;
}

The execution flow of the code is shown in the figure below: execute according to the flow of ① ②③④ ②③④ …

If step ② is true, then step ③④ will be executed cyclically

If step ② is false, the loop ends

[External link picture transfer failed, the source site may have an anti-leech link mechanism, it is recommended to save the picture and upload it directly (img-NIeyLddg-1689742908661)(assets/1661141996444.png)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-OUo0Dqzv-1689742908662)(assets/1661141867092.png)]

How to choose for and while

After learning this, careful students may find that the execution process of while loop and for loop is the same. Are they universal?

  • In terms of function: what can be done with a for loop can be done with a while loop.

  • In terms of usage specifications: if you know how many times to loop, it is recommended to use for; if you don’t know how many times to loop, it is recommended to use while

3.4 while loop case - origami case

Dear students, we have learned the basic use of while loop in the last section. Next, we will use a case to consolidate the use of the while loop. The main purpose is to let everyone know how to use the while loop to fulfill the requirements.

The case requirements are as follows:

需求:世界最高山峰珠穆朗玛峰高度是:8848.86=8848860毫米,假如我有一张足够大的它的厚度是0.1毫米。请问:该纸张折叠多少次,可以折成珠穆朗玛峰的高度?

Let's analyze what to do

分析:首先由于不知道折叠多少次,我们可以选择用while循环
	1)纸张的初始化厚度为0.1毫米,珠峰的高度为8848860毫米
		double peakHeight = 8848860;
		double paperThickness = 0.1;
	2)每次折叠纸张的厚度为原来的两倍,这是需要循环执行的
		while(纸张厚度<8848860){
    
    
			纸张厚度*=2;
		}
	3)需要求折叠的次数,可以用一个变量来记录折叠的次数
		int 次数 = 0;
		while(纸张厚度<8848860){
    
    
			纸张厚度*=2;
            次数++; //每次折叠次数累加
		}
	结果:等循环结束之后,打印记录次数的值,就是折叠多少次了。

Write the code according to the above analysis

// 1、定义变量记住珠穆朗玛峰的高度和纸张的高度。
double peakHeight = 8848860;
double paperThickness = 0.1;

// 3、定义一个变量count用于记住纸张折叠了多少次
int count = 0;

// 2、定义while循环控制纸张开始折叠
while (paperThickness < peakHeight) {
    
    
    // 把纸张进行折叠,把纸张的厚度变成原来的2倍。
    paperThickness = paperThickness * 2;
    count++;
}
System.out.println("需要折叠多少次:" + count);
System.out.println("最终纸张的厚度是:" + paperThickness);

3.5 do-while loop - format and flow

Dear students, next we will learn the third format of the loop structure - the do-while loop.

Let's first understand what the while loop looks like, and then write a basic case of the while loop according to the format.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-1pXGM8K7-1689742908664)(assets/1661143715539.png)]

As shown in the figure below: the execution flow of the do-while loop is executed in the order of ① ②③④ ②③④….

We will find that the characteristic of the do-while loop is to execute first and then judge. Even if the condition is not true, it will be executed once first.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-7n70tehN-1689742908665)(assets/1661143856132.png)]

Let's summarize the differences between the three cycles for students

1. for循环 和 while循环(先判断后执行); 
   do...while (先执行后判断)
   
2.for循环和while循环的执行流程是一模一样的,
	功能上无区别,for能做的while也能做,反之亦然。
	如果已知循环次数建议使用for循环,如果不清楚要循环多少次建议使用while循环。
	
3 for循环中控制循环的变量只在循环中使用
  while循环中,控制循环的变量在循环后还可以继续使用

3.6 Infinite loop

When students write code, they may accidentally write the code into an infinite loop. The so-called infinite loop is a loop that cannot be stopped.

Next, lead the students to know several ways of writing endless loops. Then talk about the use of an infinite loop.

//for死循环
for ( ; ; ){
    
    
    System.out.println("Hello World1");
}

//while死循环
while (true) {
    
    
    System.out.println("Hello World2");
}

//do-while死循环
do {
    
    
    System.out.println("Hello World3");
}while (true);

What are the application scenarios of the infinite loop?

The most typical is that you can use an infinite loop to make a server program. For example, Baidu's server program is always running, and you can access Baidu through a browser at any time. If one day Baidu's server stops running, it means that everyone will never be able to provide the services provided by Baidu.

For such an application, we can understand it now. For now, we only need to know how to write the code format and what effect it can achieve.

3.7 Loop nesting

Dear students, next we will learn a loop form that is very commonly used in practical work - loop nesting.

The so-called loop nesting means that a loop contains another loop (that is what students often say, Matryoshka _ ), let's demonstrate it through the case code below.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-joLCQM9Q-1689742908667)(assets/1661145140910.png)]

Loop nested execution process: every time the outer loop loops, the inner loop will be executed for one round.

i=0; i<3true; 进入循环
	//j的取值从0到5,执行一轮,打印5次"我爱你"
	for(int j = 1; j <= 5; j++) {
    
    
       System.out.println("我爱你:" + i);
    }
    内层循环执行完之后,执行外层的i++; i的值1
    
i=1时:i<3true; 进入循环
	//j的取值从0到5,又执行一轮,打印5次"我爱你"
	for(int j = 1; j <= 5; j++) {
    
    
       System.out.println("我爱你:" + i);
    }
    内层循环执行完之后,执行外层的i++; i的值2
    
i=2时:i<3true; 进入循环
	//j的取值从0到5,再执行一轮,打印5次"我爱你"
	for(int j = 1; j <= 5; j++) {
    
    
       System.out.println("我爱你:" + i);
    }
    内层循环执行完之后,执行外层的i++; i的值3
    
i=3时:i<3false; 外层循环结束

After understanding the execution process of loop nesting, let's write another case to consolidate it

需求:在控制台使用 * 打印出45列的矩形
    ****
    ****
    ****
    ****
//1)先写一个循环用来在一行中打印5个"*"
for (int j = 1; j <= 5; j++) {
    
    
    System.out.print("*"); // 不换行
}
System.out.println(); //换行


System.out.println("-----------------");

//2)再将第一步的代码套一层循环,执行4次,就可以打印4行
for (int i = 1; i <= 4; i++) {
    
    
    for (int j = 1; j <= 5; j++) {
    
    
        System.out.print("*"); // 不换行
    }
    System.out.println(); //换行
}

To sum up, it is important to understand this sentence for nested loops: every time the outer loop loops, the inner loop will be executed for one round.

3.9 Jump statement break, continue

We learned the loop structure earlier, and we also came into contact with some forms of infinite loops in the middle, so what should I do if I want to jump out of the loop early during the loop?

Here you need to use the jump statement, you need to use the break and continue keywords. Let's first understand the role of these two keywords

  • Break function: jump out and end the execution of the current loop
  • Continue function: end this cycle and enter the next cycle

Case 1: Demonstrate the use of break to terminate the execution of the loop early

// 1、break:跳出并结束当前所在循环的执行。
// 场景:假如你又有老婆了,你犯错了,你老婆罚你说:5句我爱你
// 说到第三句的时候心软了,让你别再说了。
for (int i = 1; i <= 5; i++) {
    
    
    System.out.println("我爱你:" + i);
    if(i == 3){
    
    
        // 说明已经说完了第三句了,心软了。
        break; // 跳出并结束当前所在循环的执行。
    }
}

Case 2: Demonstrate the use of continue, end one cycle in the cycle, and continue to the next cycle

// 2、continue:跳出当前循环的当次执行,直接进入循环的下一次执行。
// 场景: 假如你有老婆,你犯错了,你老婆罚你洗碗5天。
// 第三天的时候,你表现很好,第三天不用洗碗,但是不解恨,第四天还是要继续的。
for (int i = 1; i <= 5; i++) {
    
    
    if(i == 3) {
    
    
        // 已经到了第三天,第三天不用洗的。
        continue;
    }
    System.out.println("洗碗:" + i);
}

It should be noted that break and continue are not available anywhere

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-S1NWDe9m-1689742908668)(assets/1661146324812.png)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-EaCki4Hv-1689742908670)(assets/1661146405314.png)]


3.9 Summary of Loop Structures

So far, all the content about the loop structure has been learned. Let's summarize the scenarios in which several loop structures are used.

1. 什么是流程控制
	答:流程控制是用来控制程序的执行顺序的
	
2. 分支结构ifswitch,如何选择?
	答:if分支:一般用于对一个范围进行判断
		switch分支:对一个一个值进行匹配
		
3. for循环和while循环、do-while如何循环
	答:知道循环次数用for、不知道循环次数用while
	   想要先执行,再判断,用do-while

4. Recursion

Recursion (recursion) The so-called recursive method is a method that directly or indirectly calls itself.

To terminate a recursive method, the problem must finally reach a termination condition. When the problem reaches the termination condition, the result is returned to the caller. The caller then does the computation and returns the result to its own caller. This process continues until the result is returned to the original caller.

Example: Factorial Enter a non-negative integer and find the factorial of this number.

import java.util.Scanner;
public class App01{
    
    
  public static void main(String[] args){
    
    
    Scanner inp=new Scanner(System.in);
    System.out.print("请输入一个非负整数:");
    int n=inp.nextInt();
    System.out.print(n+"!="+factor(n));
  }
  //此为定义的一个方法,后面会讲,主要是以此来理解递归调用算法
  public static long factor(int n){
    
    
    if(n==0)
      return 1;
    else
      return n*factor(n-1);  //自己调用自己
  }
}

5. Exercise: Generate random numbers

Dear students, next we will learn a new knowledge - generating random numbers.

Generating random numbers is actually very practical in many scenarios. For example, in the classroom, you can write a random roll call device to call students to answer questions; for example, you can randomly draw prizes at the company annual meeting.

5.1 How to generate a random number

The function of generating random numbers, in fact, Java has provided us with a class called Random in JDK, we only need to call the functions provided by the Random class.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-In5vqetj-1689742908671)(assets/1661147570538.png)]

// 目标:掌握使用Random生成随机数的步骤。
// 1、导包。import java.util.Random; (idea会自动完成)
import java.util.Random;
public class RandomDemo1 {
    
    
    public static void main(String[] args) {
    
    
        // 2、创建一个Random对象,用于生成随机数。
        Random r = new Random();
        // 3、调用Random提供的功能:nextInt得到随机数。
        for (int i = 1; i <= 20; i++) {
    
    
            int data = r.nextInt(10); // 0 - 9
            System.out.println(data);
        }
    }
}

5.2 Guess the number game

Dear students, let's use a case to comprehensively use the previous process control, jump statement, and random number;

If you can write this case, it means that you have a good grasp of today's knowledge points.

需求:
	随机生成一个1-100之间的数据,提示用户猜测,猜大提示过大,猜小提示过小,直到猜中	  结束游戏

分析:
	1.先随机生成一个1-100之间的数据。
		谁可以帮你生成随机数啊? 是不是要用到Random2.定义一个死循环让用户可以一直猜测。
		用户猜的数据从哪里来啊? 是不是要用到Scanner?

	3.在死循环里,每次让用户录入的数据和随机数进行比较
		如果比随机数大:提示猜大了
		如果比随机数小:提示猜小了
		如果和随机数相同:提示恭喜你猜中了
import java.util.Random;
import java.util.Scanner;

public class RandomTest2 {
    
    
    public static void main(String[] args) {
    
    
        // 1、随机产生一个1-100之间的数据,做为中奖号码。
        Random r = new Random();
        int luckNumber = r.nextInt(100) + 1;

        // 2、定义一个死循环,让用户不断的猜测数据
        Scanner sc = new Scanner(System.in);
        while (true) {
    
    
            // 提示用户猜测
            System.out.println("请您输入您猜测的数据:");
            int guessNumber = sc.nextInt();

            // 3、判断用户猜测的数字与幸运号码的大小情况
            if(guessNumber > luckNumber){
    
    
                System.out.println("您猜测的数字过大~~");
            }else if(guessNumber < luckNumber){
    
    
                System.out.println("您猜测的数字过小~~");
            }else {
    
    
                System.out.println("恭喜您,猜测成功了,可以买单了~~");
                break; // 结束死循环
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/whirlwind526/article/details/131806363