4. Java process control

Insert image description here

Chapter 1 Process Control Statement

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 know the execution flow of each statement. Moreover, many times we need to control the execution order of statements to achieve the functions we want.

1.1 Classification of process control statements

​ Sequential structure

​ Judgment and selection structure (if, switch)

​ Loop structure (for, while, do…while)

1.2 Sequential structure

The sequential structure is the simplest and most basic process control in the program. There is no specific syntax structure. The codes are executed in sequence. Most of the codes in the program are executed in this way.

Sequential structure execution flow chart:

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

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 following statement content

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

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: Father-in-law chooses son-in-law

need:

​ Enter the son-in-law’s alcohol consumption with the keyboard. If it is more than 2 pounds, 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 Xiao Ming’s exam ranking. If the ranking is 1, Xiao Hong can be Xiao Ming’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 Boolean type variable, do not write ==, just write the variable directly in parentheses.

  2. If there is only one statement body in the braces, the braces can be omitted.

    If the curly braces are omitted, then if can only control the statement closest to it.

    **Suggestion:** Don't write it yourself. If someone else writes it, just 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 following statement content

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

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:

​ Enter an integer on the keyboard to represent the money on your body.

​ If it is greater than or equal to 100 yuan, it is an Internet celebrity restaurant.

​ Otherwise, just eat affordable Shaxian snacks.

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: Choosing seats in the theater

need:

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

​ Suppose a theater sells 100 tickets, and the ticket numbers 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 on the keyboard to represent the ticket number of the movie ticket.

​ Different prompts are given according to different situations:

​ If the ticket number is an odd number, then it is printed on the left.

​ If the ticket number is an even number, then it is printed 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.

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

Exercise 1: Exam Rewards

need:

​ Xiao Ming is about to take his final exam. Xiao Ming’s father told him that he would give him different gifts based on his different exam scores.

If you can control Xiao Ming's score, please use a 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. You can use keyboard input to obtain the value.

​ ② Since there are many types of rewards and they belong to a variety of judgments, they are implemented in the if...else...if format.

③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 Pushing stroke:

  • First calculate the value of the expression
  • Secondly, it is compared with the case in sequence. 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 all cases do not match the value of the expression, the default statement body will be executed, and the program will end.
Exercise: Exercise Program
  • Requirements: Enter the week number with the keyboard and display today's weight loss activities.

    Monday: Running

    Tuesday: swimming

    Wednesday: Walk slowly

    Thursday: Spinning Bike

    Friday: Boxing

    Saturday: Mountain climbing

    Sunday: Have 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 anywhere or omitted

  • case penetration

    Not writing break will cause case penetration phenomenon

  • 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 respective 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 list a limited amount of data and select one of them for execution, we use the switch statement

for example:

​ For Xiao Ming’s test scores, 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, month, or the function selection from 0 to 9 in the customer service phone number, you can use switch.

Practice: Rest days and working days

Requirements: Use the keyboard to input the day of the week 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 section of code when the loop condition is met. This repeatedly executed code is called a loop body statement. When this loop body is executed repeatedly, the loop judgment condition needs to be modified at the appropriate time. is false, thereby 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: 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: used to express the conditions for repeated execution of the loop. Simply put, it is to judge whether the loop can continue to execute.
  • Loop body statement: used to express the content of repeated execution of the loop. Simply put, it is what the loop repeatedly executes.
  • Conditional control statement: used to express the content of each change in the execution of the loop. Simply put, it controls whether the loop can be executed.

Implementation process:

①Execute initialization statement

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

​ If it is false, the loop ends

​ If it is true, continue execution

③Execute the loop body statement

④Execute conditional control statements

⑤Return to ②Continue

for loop writing skills:

  • Determine the starting condition of the loop
  • Determine the end condition of the loop
  • Determine 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 the data of 1-5 and 5-1 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 summation 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);
    }
}
  • Key points of this question:
    • If the requirements you encounter in the future include the word summation, please immediately think of the summation variable.
    • The definition position of the summation 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 summation 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 - counting times

need:

​ Enter two numbers on the keyboard to represent a range.

​ Statistics are within this range.

How many numbers are there that are both divisible by 3 and divisible by 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: 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 Differences 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 loop range.

​ 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/haodian666/article/details/134982765