2. JAVA branch structure switch structure for loop

1 branch structure

1.1 Overview
Although the program of sequential structure can solve problems such as calculation and output
, it cannot make judgment and then choose. For problems that need to be judged first and then selected, the branch structure should be used

1.2 Form

insert image description here

说明:条件表达式必须是布尔表达式(关系表达式或逻辑表达式)或 布尔变量。

Implementation process:

  1. First judge the conditional expression to see if the result is true or false
  2. If true, execute the statement block
  3. If false, the statement block is not executed

Please add a picture description

结构 2::if...else

Format:

if(条件表达式) {
    
    
 语句块 1; }else {
    
    
 语句块 2; }

执行流程:

  1. First judge the conditional expression to see if the result is true or false
  2. If true execute statement block 1
  3. If false execute block 2

Please add a picture description

1.3.1 Exercise: Example of product discount

Create package: cn.tedu.basic
Create class: TestDiscount.java
Requirement: Receive the original price input by the user. 10% off for orders over 1000; 20% off for orders over 2000; 50% off for orders over 5000

package cn.tedu.basic;

import java.util.Scanner;

/**需求:接收用户输入的原价,满1000打9折,满2000打8折,满5000打5折*/
public class TestDiscount {
    
    
	public static void main(String[] args) {
    
    
		//1.提示用户输入原价
		System.out.println("请输入商品原价:");
		//2.接收用户输入的原价
		double price = new Scanner(System.in).nextDouble();                     
		//3.计算打折后的价格
		//3.1定义变量用来保存打折后的价格
		double count = price;//初始值是商品的原价
		//3.2判断用户的打折段位并打折
		if(price >= 5000) {
    
    //满5000
			count = price *0.5;//打5折
		}else if(price >= 2000) {
    
    //满2000
			count = price * 0.8;//打折8折
		}else if(price >= 1000) {
    
    //满1000
			count = price *0.9;//打9折
		}
//		if(1000 <= price && price< 2000) {
    
    
//			count = price *0.9;
//		}else if(2000 <= price && price < 5000) {
    
    
//			count = price * 0.8;
//		}else if(price >= 5000) {
    
    
//			count = price *0.5;
//		}
		//3.3输出用户实际支付的价格
		System.out.println("您实际应该支付:"+count);
	}
}

1.3.2 Exercise: A case of a statistician scoring a rank

package cn.tedu.basic;

import java.util.Scanner;

/*本类用于判断学员分数的档位*/
public class TestScore {
    
    
	public static void main(String[] args) {
    
    
		//1.提示并接收学员的分数
		System.out.println("请输入你的分数:");
		int score = new Scanner(System.in).nextInt();
		/*90分及以上  优秀
		 *80-89 良好
		 *70-79 中等
		 *60-69 及格
		 *60分及以下 不及格 */
		
		/**为了增强程序的健壮性,如果用户输入的数据不符合规则,就结束*/
		if(score <0 || score >100 ) {
    
    
			System.out.println("输入数据不合法,请重新输入!!!");
		}else {
    
    
			//2.判断分数的段位,并输出结果
			if(score >= 90) {
    
    //大于90
				System.out.println("优秀!");
			//}else if(score>=80 && score <=89) {
    
    
			}else if(score>=80) {
    
    //[80,90)
				System.out.println("良好!");
			}else if(score>=70) {
    
    //[70,80)
				System.out.println("中等!");
			}else if(score>=60) {
    
    //[60,70)
				System.out.println("及格!");
			}else {
    
    //小于60
				System.out.println("不及格!");
			}
		}	
	}
}

practise:

定义两个整数,分别为 small 和 big,如果第一个整数 small 大于第二个整数 big,就交换。输出显示 small 和 big 变量的值。

public class IfElseExer3 {
    
    
 public static void main(String[] args) {
    
    
 int small = 10;
 int big = 9;
 if (small > big) {
    
    
 int temp = small;
 small = big;
 big = temp;
 }
 System.out.println("small=" + small + ",big=" + big);
 } 

}

practise:

编写程序,声明 2 个 int 型变量并赋值。判断两数之和,如果大于等于 50,打印“hello world!”

public class IfElseExer5 {
    
    
 public static void main(String[] args) {
    
    
 int num1 = 12, num2 = 32;
 
 if (num1 + num2 >= 50) {
    
    
 System.out.println("hello world!");
 }
 } 
}

2 switch structure

执行流程

第 1 步:According to the value of the expression in the switch, each case is matched in turn. If the value of the expression is equal to
the constant value in a certain case, execute the execution statement in the corresponding case.
第 2 步:After executing the execution statement of this case,
情况 1:if a break is encountered, it will execute the break and jump out of the current switch-case structure
情况 2:. If no break is encountered, it will continue to execute the execution statements in other cases after the current case.
—>case penetration... Until the break keyword is encountered or all the execution statements of the case and default are executed, jump out of the current
switch-case structure

2.1 Overview
The switch case statement is used to judge whether a variable is equal to a certain value in a series of values, and each value is called a branch.
When a case is established, all cases, including default, are penetrated backwards from this case until the end of the program or the break program is encountered.

2.2 Form

insert image description here

2.3 Exercise: Number Matching

Create package: cn.tedu.basic
Create class: TestSwitch.java

package cn.tedu.basic;
/*本类用于练习switch结构*/
/**总结:
 * 1.变量a的类型byte short char int String
 * 2.会拿着变量a的值依次与case后的值做比较,如果不加break,
 *        会向后穿透所有case,包括default
 * 3.如果设置了default“保底选项”,并且没有任何case匹配到的话,就执行default
 * 4.break与default是可选项,根据具体业务来决定加不加
 * */
public class TestSwitch {
    
    
	//1.创建程序的入口函数main
	public static void main(String[] args) {
    
    
		//2.定义一个变量
		int a = 19;
		//3.完成switch结构的测试
		switch(a) {
    
    
			case 1 : System.out.println(1);break;
			case 2 : System.out.println(2);break;
			case 3 : System.out.println(3);break;
			case 4 : System.out.println(4);break;
			case 5 : System.out.println(5);break;
			default : System.out.println(0);
		}		
	}
	
}

2.4 Exercise: String type in Switch

Use class: TestSwitch.java

package cn.tedu.basic2;
/**本类用来测试switch结构2*/
public class TestSwitch2 {
    
    
	public static void main(String[] args) {
    
    
		String day = "星期五";
		switch(day) {
    
    
			case "星期一" : System.out.println("星期一吃四川火锅");break;
			case "星期二" : System.out.println("星期二吃齐齐哈尔烤肉");break;
			case "星期三" : System.out.println("星期三吃新疆羊肉串");break;
			case "星期四" : System.out.println("星期四吃阳澄湖大闸蟹");break;
			case "星期五" : System.out.println("星期五吃兰州拉面");break;
			case "星期六" : System.out.println("星期六吃南昌拌粉");break;
			case "星期日" : System.out.println("星期日吃武汉藕汤");break;
			default : System.out.println("想吃点啥吃点啥吧~");
		}
	}
}

2.5 Precautions for switch structure

The variable types in the switch statement can be: byte, short, int, char, String (supported after jdk1.7)
The switch statement can have multiple case statements
1. Each case is followed by a value to be compared and a colon, and this The data type of the value must be consistent with the data type of the variable.
2. When the variable value is equal to the value of the case statement, start to execute the content of the case statement. After execution, it will judge whether there is a break in this line of code
. There will be a case penetration phenomenon;
4. If there is, the execution will end, if not, it will continue to execute backwards and penetrate all cases, including default
5. The switch statement can contain a default branch, which is generally written at the end of the switch statement
6. If there is a break in the case before the default, the default will not be executed

Use of lamabada expression in switch case

When using lamabada expressions, be sure to change jdk to jdk12 or above

Please add a picture description

package com.cy;

public class Gh {
    
    

    public static void main(String[] args) {
    
    
    
        int a=1;

        switch (a){
    
    

            case 1  -> System.out.println("今天是星期一");
            case 2  -> System.out.println("今天是星期二");
            case 3  -> System.out.println("今天是星期三");
            case 5  -> System.out.println("今天是星期五");
            default -> System.out.println("今天是星期六");
        }
        }
    }

3 loop structure

3.1 Overview of for
The loop structure refers to a program structure that needs to execute a certain function repeatedly in the program.
It judges whether to continue to execute a certain function or to exit the loop by the conditions in the loop body.
According to the judgment condition, the loop structure can be subdivided into the loop structure of judging first and then executing and the loop structure of executing first and then judging.

3.2 for form

insert image description here

3.3 for loop execution order

We obviously only wrote one print statement, why did we print multiple numbers?
I hope the following figure can help you understand the execution sequence of the for loop:

insert image description here

说明:

• Two in for(;;); no more and no less
• ①The initialization part can declare multiple variables, but they must be of the same type, separated by commas
• ②The loop condition part is a boolean type expression, when the value is When false, exit the loop
④ There can be multiple variable updates, separated by commas

3.4 Exercise: print slogon 100 times/print 0 to 10/print 10 to 0/print 8,88,888,8888,

package cn.tedu.basic;
/**本类用来测试循环结构for循环*/
public class TestFor {
    
    
	public static void main(String[] args) {
    
    
		//需求:打印100次自己的宣言
		//for(开始条件;循环条件;更改条件){循环体;}
		for(int i = 1;i<=100;i++) {
    
    
			System.out.println(“又不是没那条件,干就完啦!”);
		}
		//需求:打印0到10
		//for(开始条件;循环条件;更改条件){循环体;}
		//0 1 2 3 4 5 6 7 8 9 10
		//从哪开始:0
		//到哪结束:10
		//怎么变化:+1 ++
		for(int i = 0;i<=10;i++) {
    
    
			System.out.println(i);
		}
		System.out.println("**********************");
		//需求:打印10到0
		//10 9 8 7 6 5 4 3 2 1 0
		//从哪开始:10
		//到哪结束:0
		//怎么变化:-1  --
		//for(开始条件;循环条件;更改条件){循环体}
		for(int i = 10 ;i >= 0;i--) {
    
    
			System.out.println(i);
		}
		//需求:打印8,88,888,8888,
		//8 88 888 8888
		//从何开始:8
		//到哪结束:8888
		//如何变化:*10+8
		for(int i =8 ; i <= 8888 ; i=i*10+8) {
    
    
			System.out.print(i+",");//使用的是print(),打印后不换行
		}
	}
}

3.5 Exercise: Find the sum of elements within [1,100], the sum of even numbers, and the number of even numbers

package cn.tedu.basic;
/*本类用于测试for循环结构2*/
public class TestFor2 {
    
    
	public static void main(String[] args) {
    
    
		//m1();
		//m2();
		m3();
	}
	/*需求:求出1-100以内所有偶数的个数*/
	private static void m3() {
    
    
		//1.定义变量用来保存偶数的个数
		int count = 0;
		//2.创建循环,依次循环1-100范围内的数
		for(int i = 1;i<101;i++) {
    
    
			//3.过滤出来要统计个数的偶数
			if(i % 2 ==0) {
    
    //说明这是一个偶数
				//4.对偶数的个数进行累计
				//count = count +1;
				count++;
				//++count;
			}
		}
		//5.打印最终统计的个数
		System.out.println(count);
	}
	/*需求:求出1-100以内所有偶数的和*/
	private static void m2() {
    
    
		//1.定义变量用来保存最终求和的结果
		int sum = 0;
		//2.创建循环,依次循环1-100范围内的数
		for(int i = 1;i <101;i++) {
    
    
			//3.过滤出来需要累加的偶数
			if(i%2 == 0) {
    
    
			//if(i%2 == 1) {//过滤奇数
				//4.能进来,说明是偶数,累加
				sum = sum +i;
			}
		}
		//5.在for循环结束以后,打印所有偶数累加的和
		System.out.println(sum);
	}
	/*需求:求出1-100以内所有数的和*/
	private static void m1() {
    
    
		//1.定义一个变量用来保存求和的结果
		int sum = 0;
		//2.创建循环,依次循环1-100范围内的数
		for(int i = 1;i<=100;i++) {
    
    
			//3.将本轮循环到的数字累加到最终的结果中
			sum = sum + i;
		}
		//4.打印最终累加的结果
		System.out.println(sum);
	}
}

4 Expansion
If you want to see what the loop is executing, you can also use the tool:

Guess you like

Origin blog.csdn.net/weixin_58276266/article/details/131460443