[Twelve days to learn java] day04-process control statement

Chapter 1 Flow Control Statements

During the execution of a program, the execution order of each statement has a direct impact on the result of the program. Therefore, we must be clear about the execution flow of each statement. Moreover, in many cases, we need to control the execution order of statements to achieve the functions we want.

1.1 Classification of flow control statements

sequential structure

Judgment and selection structure (if, switch)

Loop structure (for, while, do...while)

1.2 Sequence structure

The sequence structure is the simplest and most basic flow control in the program. There is no specific grammatical structure. It is executed in sequence according to the sequence of the codes. Most of the codes in the program are executed in this way.

Sequential structure execution flow chart:

insert image description here

Chapter 2 Judgment statement: if statement

2.1 if statement format 1

格式:
if (关系表达式) {
    语句体;	
}

Implementation process:

① First calculate the value of the relational expression

②If the value of the relational expression is true, execute the statement body

③ If the value of the relational expression is false, the statement body will not be executed

④Continue to execute the content of the following statement

Example:

public class IfDemo {
	public static void main(String[] args) {
		System.out.println("开始");	
		//定义两个变量
		int a = 10;
		int b = 20;	
		//需求:判断a和b的值是否相等,如果相等,就在控制台输出:a等于b
		if(a == b) {
			System.out.println("a等于b");
		}		
		//需求:判断a和c的值是否相等,如果相等,就在控制台输出:a等于c
		int c = 10;
		if(a == c) {
			System.out.println("a等于c");
		}		
		System.out.println("结束");
	}
}

Exercise 1: The father-in-law chooses the son-in-law

need:

Key in the drinking capacity of the son-in-law, if it is more than 2 catties, the father-in-law will give a response, otherwise there will be no response

Code example:

//分析:
//1.键盘录入女婿的酒量
Scanner sc = new Scanner(System.in);
System.out.println("请输入女婿的酒量");
int wine = sc.nextInt();//5
//2.对酒量进行一个判断即可
if(wine > 2) {
    System.out.println("不错哟,小伙子!");
}

Exercise 2: Exam Rewards

need:

Enter an integer on the keyboard, indicating Xiaoming's exam ranking. If the ranking is 1, Xiaohong can be Xiaoming's girlfriend.

Code example:

//分析:
//1.键盘录入一个整数,表示小明的考试名次
Scanner sc = new Scanner(System.in);
System.out.println("请输入小明的名次");
int rank = sc.nextInt();
//2.对小明的考试成绩进行判断即可
if(rank == 1){
    System.out.println("小红成为了小明的女朋友");
}

Details of the first format:

  1. If we want to judge a variable of Boolean type, don't write ==, just write the variable in parentheses.
  1. If there is only one statement body in the curly braces, then the curly braces can be omitted.
    If the curly braces are omitted, then if can only control the statement closest to him.
    Suggestion: Don't write it yourself. If someone else writes it like this, you just need to be able to understand it.

2.2 if statement format 2

格式:
if (关系表达式) {
    语句体1;	
} else {
    语句体2;	
}

Implementation process:

① First calculate the value of the relational expression

② If the value of the relational expression is true, execute statement body 1

③ If the value of the relational expression is false, execute statement body 2

④Continue to execute the content of the following statement

[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-etlsPk8e-1679393370385)(null)]

Example:

public class IfDemo02 {
	public static void main(String[] args) {
		System.out.println("开始");		
		//定义两个变量
		int a = 10;
		int b = 20;
		//需求:判断a是否大于b,如果是,在控制台输出:a的值大于b,否则,在控制台输出:a的值不大于b
		if(a > b) {
			System.out.println("a的值大于b");
		} else {
			System.out.println("a的值不大于b");
		}		
		System.out.println("结束");
	}
}

Exercise 1: Eat

need:

The keyboard enters an integer representing the money on the body.

       如果大于等于100块,就是网红餐厅。




       否则,就吃经济实惠的沙县小吃。

Code example:

//分析:
//1.键盘录入一个整数。表示身上的钱。
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数表示身上的钱");
int money = sc.nextInt();
//2.对钱进行判断
if(money >= 100){
    System.out.println("吃网红餐厅");
}else{
    System.out.println("福建大酒店");
}

Exercise 2: Theater seat selection

need:

In actual development, the if judgment will also be used for movie theater seat selection.

Assume that a theater has sold 100 tickets, and the serial numbers of the tickets are 1~100.

Among them, odd-numbered ticket numbers sit on the left side, and even-numbered ticket numbers sit on the right side.

Enter an integer from the keyboard to represent the ticket number of the movie ticket.

According to different situations, different prompts are given:

If the ticket number is odd, then print to the left.

If the ticket number is even, then the print sits on the right.

Code example:

//分析:
//1.键盘录入票号
Scanner sc = new Scanner(System.in);
System.out.println("请输入票号");
int ticket = sc.nextInt();
if(ticket >= 1 && ticket <= 100){
    //合法
    //2.对票号进行判断
    if (ticket % 2 == 0) {
        //偶数
        System.out.println("坐右边");
    } else {
        //奇数
        System.out.println("坐左边");
    }
}else{
    //票号不合法
    System.out.println("票号不合法");
}

2.3 if statement format 3

格式:
if (关系表达式1) {
    语句体1;	
} else if (关系表达式2) {
    语句体2;	
} 
else {
    语句体n+1;
}

Implementation process:

① First calculate the value of relational expression 1

②If the value is true, execute statement body 1; if the value is false, calculate the value of relational expression 2

③ If the value is true, execute statement body 2; if the value is false, calculate the value of relational expression 3

④…

⑤ If no relational expression is true, execute statement body n+1.

[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-qyEQStZ9-1679393370536)(null)]

Exercise 1: Exam Rewards

need:

Xiao Ming's final exam is coming soon, and Xiao Ming's father told him that he will give him different gifts according to his different test scores,

If you can control Xiao Ming's score, please use the program to realize what kind of gift Xiao Ming should get, and output it on the console.

analyze:

①Xiao Ming’s test score is unknown, and the value can be obtained by keyboard input

②Because there are many types of rewards, which belong to multiple judgments, the if...else...if format is used to realize

③Set corresponding conditions for each judgment

④ Set corresponding rewards for each judgment

Code example:

//95~100 自行车一辆
//90~94   游乐场玩一天
//80 ~ 89 变形金刚一个
//80 以下  胖揍一顿

//1.键盘录入一个值表示小明的分数
Scanner sc = new Scanner(System.in);
System.out.println("请输入小明的成绩");
int score = sc.nextInt();
//2.对分数的有效性进行判断
if(score >= 0 && score <= 100){
    //有效的分数
    //3.对小明的分数进行判断,不同情况执行不同的代码
    if(score >= 95 && score <= 100){
        System.out.println("送自行车一辆");
    }else if(score >= 90 && score <= 94){
        System.out.println("游乐场玩一天");
    }else if(score >= 80 && score <= 89){
        System.out.println("变形金刚一个");
    }else{
        System.out.println("胖揍一顿");
    }
}else{
    //无效的分数
    System.out.println("分数不合法");
}

Chapter 3 switch statement

3.1 Format

switch (表达式) {
	case 1:
		语句体1;
		break;
	case 2:
		语句体2;
		break;
	...
	default:
		语句体n+1;
		break;
}

3.2 Execution process:

  • First evaluate the expression
  • Secondly, it is compared with the case in turn. Once there is a corresponding value, the corresponding statement will be executed. During the execution, it will end when a break is encountered.
  • Finally, if none of the cases match the value of the expression, the body of the default statement is executed, and the program ends.

Exercise: Exercise Program

  • Requirement: keyboard entry week number, display today's weight loss activities.
    Monday: Run
    Tuesday: Swim
    Wednesday: Walk
    Thursday: Spinning
    Friday: Boxing
    Saturday: Hill Climb
    Sunday: Eat a Good Meal
  • Code example:
package a01switch选择语句;

import java.util.Scanner;

public class SwitchDemo2 {
    public static void main(String[] args) {
        //1.键盘录入一个整数表示星期
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数表示星期");
        int week = sc.nextInt();

        //2.书写一个switch语句去跟week进行匹配
        switch (week){
            case 1:
                System.out.println("跑步");
                break;
            case 2:
                System.out.println("游泳");
                break;
            case 3:
                System.out.println("慢走");
                break;
            case 4:
                System.out.println("动感单车");
                break;
            case 5:
                System.out.println("拳击");
                break;
            case 6:
                System.out.println("爬山");
                break;
            case 7:
                System.out.println("好好吃一顿");
                break;
            default:
                System.out.println("输入错误,没有这个星期");
                break;
        }
    }
}

3.3 Extended knowledge of switch:

  • The position and omission of default
    default can be placed in any position, and can also be omitted
  • Case penetration
    If no break is written, case penetration will occur
  • New features of switch in JDK12
int number = 10;
switch (number) {
    case 1 -> System.out.println("一");
    case 2 -> System.out.println("二");
    case 3 -> System.out.println("三");
    default -> System.out.println("其他");
}
  • The usage scenarios of the third format of switch and if

When we need to judge a range, use the third format of if

When we enumerate a limited number of data and select one of them to execute, use the switch statement

for example:

For Xiao Ming's test results, if you use switch, you need to write 100 cases, which is too troublesome, so it is simple to use if.

If it is the day of the week, the month, the function selection of 0~9 in the customer service call can use the switch

Practice: rest days and work days

Requirements: Enter the number of weeks with the keyboard, and output working days and rest days.

(1-5) working days, (6-7) rest days.

Code example:

//分析:
//1.键盘录入星期数
Scanner sc = new Scanner(System.in);
System.out.println("请输入星期");
int week = sc.nextInt();//3
//2.利用switch进行匹配
----------------------------------------------------
利用case穿透简化代码
switch (week){
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        System.out.println("工作日");
        break;
    case 6:
    case 7:
        System.out.println("休息日");
        break;
    default:
        System.out.println("没有这个星期");
        break;
}
----------------------------------------------------
利用JDK12简化代码书写
switch (week) {
    case 1, 2, 3, 4, 5 -> System.out.println("工作日");
    case 6, 7 -> System.out.println("休息日");
    default -> System.out.println("没有这个星期");
}

Chapter 4 Loop Structure

4.1 for loop structure (master)

A loop statement can repeatedly execute a certain piece of code when the loop condition is satisfied. This piece of code that is repeatedly executed is called a loop body statement. When the loop body is repeatedly executed, it is necessary to modify the loop judgment condition to false, thus ending the loop, otherwise the loop will continue to execute, forming an infinite loop.

4.1.1 for loop format:

for (初始化语句;条件判断语句;条件控制语句) {
	循环体语句;
}

Format explanation:

  • Initialization statement: It is used to indicate the initial state when the loop is started. Simply put, it is what it looks like when the loop starts
  • Conditional judgment statement: It is used to express the condition for repeated execution of the loop. Simply put, it is to judge whether the loop can be executed forever
  • Loop body statement: It is used to express the content of the repeated execution of the loop, in short, it is the thing that is repeatedly executed in the loop
  • Conditional control statement: used to indicate the content of each change in the loop execution, in short, it is to control whether the loop can be executed

Implementation process:

①Execute the initialization statement

② Execute the conditional judgment statement to see if the result is true or false

        如果是false,循环结束




        如果是true,继续执行

③ Execute the loop body statement

④Execute conditional control statement

⑤Back to ②Continue

For loop writing skills:

  • Determine the start condition of the loop
  • Determine the end condition of the loop
  • Determines the code to be executed repeatedly by the loop

Code example:

//1.确定循环的开始条件
//2.确定循环的结束条件
//3.确定要重复执行的代码

//需求:打印5次HelloWorld
//开始条件:1
//结束条件:5
//重复代码:打印语句

for (int i = 1; i <= 5; i++) {
    System.out.println("HelloWorld");
}
for loop exercise - output data
  • Requirement: Output 1-5 and 5-1 data on the console
  • Sample code:
public class ForTest01 {
    public static void main(String[] args) {
		//需求:输出数据1-5
        for(int i=1; i<=5; i++) {
			System.out.println(i);
		}
		System.out.println("--------");
		//需求:输出数据5-1
		for(int i=5; i>=1; i--) {
			System.out.println(i);
		}
    }
}
for loop exercise - summation
  • Requirement: Find the sum of data between 1-5, and output the sum result on the console
  • Sample code:
public class ForTest02 {
    public static void main(String[] args) {
		//求和的最终结果必须保存起来,需要定义一个变量,用于保存求和的结果,初始值为0
		int sum = 0;
		//从1开始到5结束的数据,使用循环结构完成
		for(int i=1; i<=5; i++) {
			//将反复进行的事情写入循环结构内部
             // 此处反复进行的事情是将数据 i 加到用于保存最终求和的变量 sum 中
			sum = sum + i;
			/*
				sum += i;	sum = sum + i;
				第一次:sum = sum + i = 0 + 1 = 1;
				第二次:sum = sum + i = 1 + 2 = 3;
				第三次:sum = sum + i = 3 + 3 = 6;
				第四次:sum = sum + i = 6 + 4 = 10;
				第五次:sum = sum + i = 10 + 5 = 15;
			*/
		}
		//当循环执行完毕时,将最终数据打印出来
		System.out.println("1-5之间的数据和是:" + sum);
    }
}
  • Main points of this question:
    • In the future requirements, if there is the word summation, please immediately think of the summation variable
    • The definition position of the sum variable must be outside the loop, if it is inside the loop, the calculated data will be wrong
for loop exercise - finding the sum of even numbers
  • Requirement: Find the sum of even numbers between 1-100, and output the sum result on the console }
  • Sample code:
public class ForTest03 {
    public static void main(String[] args) {
		//求和的最终结果必须保存起来,需要定义一个变量,用于保存求和的结果,初始值为0
		int sum = 0;
		//对1-100的数据求和与1-5的数据求和几乎完全一样,仅仅是结束条件不同
		for(int i=1; i<=100; i++) {
			//对1-100的偶数求和,需要对求和操作添加限制条件,判断是否是偶数
			if(i%2 == 0) {
                //sum += i;
				sum = sum + i;
			}
		}
		//当循环执行完毕时,将最终数据打印出来
		System.out.println("1-100之间的偶数和是:" + sum);
    }
}
for loop exercise - statistics

need:

The keyboard enters two numbers, indicating a range.

      统计这个范围中。




      既能被3整除,又能被5整除数字有多少个?

Code example:

4.2 while loop

4.2.1 Format:

初始化语句;
while(条件判断语句){
	循环体;
	条件控制语句;
}
Exercise 1: Print HelloWorld 5 times
int i = 1;
while(i <= 5){
    System.out.println("HelloWorld");
    i++;
}
System.out.println(i);
Exercise 2: Mount Everest
//1.定义一个变量表示珠穆朗玛峰的高度
int height = 8844430;
//2.定义一个变量表示纸张的厚度
double paper = 0.1;

//定义一个计数器(变量),用来统计折叠的次数
int count = 0;

//3.循环折叠纸张
//只有纸张的厚度 < 穆朗玛峰的高度 循环才继续,否则循环就停止
//坑:只有判断为真,循环才会继续
while(paper < height){
    //折叠纸张
    paper = paper * 2;
    count++;
}

//4.打印一下纸张的厚度
System.out.println(count);//27

4.3 do...while loop

Just understand this knowledge point

Format:

初始化语句;
do{
    循环体;
    条件控制语句;
}while(条件判断语句);

Features:

Execute first, judge later.

4.4 The difference between the three formats:

For and while loops are judged first and then executed.

do...while is executed first, and then judged.

Use a for loop when you know the number of loops or the range of loops.

When you don't know the number of loops or the scope of the loop, but you know the end condition of the loop, use a while loop.

Guess you like

Origin blog.csdn.net/weixin_60257072/article/details/129694255