2023 latest version of JavaSE tutorial - Day 3: Sequential statements and branch statements of flow control statements

The flow control statement is used to control each 语句执行顺序 statement in the program. The statements can be combined into small logical modules capable of 完成一定功能. 三种 process structure specified in programming, that is:

1. Sequential structure. The program is executed line by line from top to bottom, without any judgments or jumps in between.
2. Branch structure. Selectively execute a certain piece of code based on conditions. There are two branch statements: if…else and switch-case.
3. Loop structure. Repeatedly execute a certain code based on the loop condition. There are three types of loop statements: for, while, and do-while. Supplement: JDK5.0 provides the foreach loop to conveniently traverse collection and array elements.

Examples of process control in daily life and industrial production:

1. Sequential structure

The sequence structure is the execution of the program 从上到下逐行. Expression statements are executed sequentially. And the modification of a variable in the previous line will have an impact on the next line.
Insert image description here

public class StatementTest{
    
    
	public static void main(String[] args){
    
    
		int x = 1;
		int y = 2;
		System.out.println("x = " + x);		
        System.out.println("y = " + y);	
        //对x、y的值进行修改
        x++;
        y = 2 * x + y;
        x = x * 10;	
        System.out.println("x = " + x);
        System.out.println("y = " + y);
    }
}

Use legal 前向引用 when defining variables in Java. Such as:

public static void main(String[] args) {
    
    
	int num1 = 12;
	int num2 = num1 + 2;
}

Error form:

public static void main(String[] args) {
    
    
	int num2 = num1 + 2;
	int num1 = 12;
}

2. Branch statement

2.1 if-else conditional judgment structure

2.1.1 Basic syntax

Structure 1: Single branch conditional judgment: if, the syntax format is as follows:

if(条件表达式){
  	语句块;

说明:The conditional expression must be a Boolean expression (relational or logical expression) or a Boolean variable. Implementation process:

  1. First, judge the conditional expression to see whether the result is true or false.

  2. If true, execute the statement block

  3. If it is false, the statement block will not be executed.

    Insert image description here

Structure 2: Double-branch conditional judgment: if...else, the syntax format is as follows:

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

Implementation process:

  1. First, judge the conditional expression to see whether the result is true or false.
  2. If true, execute statement block 1
  3. If it is false, execute statement block 2
    Insert image description here

Structure 3: Multi-branch conditional judgment: if…else if…else, the syntax format is as follows:

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

Description: Once the conditional expression is true, the corresponding statement block will be executed. After executing the corresponding statement block, jump out of the current structure. Implementation process:

  1. First, judge relational expression 1 to see whether the result is true or false.
  2. If it is true, execute statement block 1, and then end the current multi-branch
  3. If it is false, continue to evaluate relational expression 2 to see whether the result is true or false.
  4. If it is true, execute statement block 2, and then end the current multi-branch
  5. If it is false, continue to evaluate the relational expression...see whether the result is true or false
  6. If no relational expression is true, block n+1 is executed and the current multi-branch is terminated.
    Insert image description here

2.1.2 Application examples

Case 1: The normal range of heart rate for adults is 60-100 beats per minute. During physical examination, if the heart rate is not within this range, it will prompt the need for further examination.

public class IfElseTest1 {
    
    
    public static void main(String[] args){
    
    
        int heartBeats = 89;

        if(heartBeats < 60 || heartBeats > 100){
    
    
            System.out.println("你需要做进一步的检查");
        }

        System.out.println("体检结束");
    }
}

Case 2: Define an integer and determine whether it is an even number or an odd number

public class IfElseTest2 {
    
    
    public static void main(String[] args){
    
    
        int a = 10;

        if(a % 2 == 0) {
    
    
            System.out.println(a + "是偶数");
        } else{
    
    
            System.out.println(a + "是奇数");
        }
    }
}

Case 3:

/*岳小鹏参加Java考试,他和父亲岳不群达成承诺:
如果:
成绩为100分时,奖励一辆跑车;
成绩为(80,99]时,奖励一辆山地自行车;
当成绩为[60,80]时,奖励环球影城一日游;
其它时,胖揍一顿。

说明:默认成绩是在[0,100]范围内*/
public class IfElseTest3 {
    
    
    public static void main(String[] args) {
    
    

        int score = 67;//岳小鹏的期末成绩
        //写法一:默认成绩范围为[0,100]
        if(score == 100){
    
    
            System.out.println("奖励一辆跑车");
        }else if(score > 80 && score <= 99){
    
        //错误的写法:}else if(80 < score <= 99){
    
    
            System.out.println("奖励一辆山地自行车");
        }else if(score >= 60 && score <= 80){
    
    
            System.out.println("奖励环球影城玩一日游");
        }
        //else{
    
    
        //	System.out.println("胖揍一顿");
        //}


        //写法二:
        // 默认成绩范围为[0,100]
        if(score == 100){
    
    
            System.out.println("奖励一辆跑车");
        }else if(score > 80){
    
    
            System.out.println("奖励一辆山地自行车");
        }else if(score >= 60){
    
    
            System.out.println("奖励环球影城玩一日游");
        }else{
    
    
            System.out.println("胖揍一顿");
        }
    }
}

Program analysis:
Insert image description here
Insert image description hereWhen the conditional expressions are in the 互斥 relationship (that is, there is no intersection with each other), the order between the conditional judgment statement and the execution statement It doesn't matter. When the relationship between conditional expressions is 包含, 小上大下/子上父下, otherwise conditional expressions with a small scope will not be executed.

2.1.3 if…else nesting

In the if statement block, or in the else statement block, another conditional judgment (can be single branch, double branch, or multiple branches) is included, which constitutes嵌套结构. Execution characteristics:

  1. If it is nested in an if statement block, only when the external if condition is met, the internal condition will be judged.
  2. If it is nested in an else statement block, only when the external if condition is not satisfied and the else is entered, the internal condition will be judged.

Case 4: Enter three integers from the keyboard and store them in variables num1, num2, and num3 respectively. Sort them (use if-else if-else), and sort them from small to small. Big output.

class IfElseTest4 {
    
    
	public static void main(String[] args) {
    
    
		
			//声明num1,num2,num3三个变量并赋值
			int num1 = 23,num2 = 32,num3 = 12;

			if(num1 >= num2){
    
    
				
				if(num3 >= num1)
					System.out.println(num2 + "-" + num1 + "-" + num3);
				else if(num3 <= num2)
					System.out.println(num3 + "-" + num2 + "-" + num1);
				else
					System.out.println(num2 + "-" + num3 + "-" + num1);
			}else{
    
     //num1 < num2
				
				if(num3 >= num2){
    
    
					System.out.println(num1 + "-" + num2 + "-" + num3);
				}else if(num3 <= num1){
    
    
					System.out.println(num3 + "-" + num1 + "-" + num2);
				}else{
    
    
					System.out.println(num1 + "-" + num3 + "-" + num2);
				}
			}
	}
}

2.1.4 Other instructions

When the statement block has only one execution statement, the pair {} can be omitted, but it is recommended to retain it. When the if-else structure is 多选一, the last else是可选的 can be omitted as needed.

2.1.5 Exercise

Exercise 1:

//1)对下列代码,若有输出,指出输出结果。
int x = 4;
int y = 1;
if (x > 2) {
    
    
       if (y > 2) 
            System.out.println(x + y);
       		System.out.println("atguigu");
} else
       System.out.println("x is " + x);

Exercise 2:

boolean b = true;
//如果写成if(b=false)能编译通过吗?如果能,结果是?
if(b == false) 	 //建议:if(!b)
	System.out.println("a");
else if(b)
	System.out.println("b");
else if(!b)
	System.out.println("c");
else
	System.out.println("d");

Exercise 3: Define two integers, small and big. If the first integer small is greater than the second integer big, swap them. The output shows the values ​​of the small and big variables.

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);
    }
}

Exercise 4: Xiao Ming takes the final Java exam and determines his Java level based on the exam results. The score range is [0,100]

/*90-100      优秀
80-89        好
70-79        良
60-69        及格
60以下    不及格*/
import java.util.Scanner;
//写法一:
public class IfElseExer4 {
    
    
    public static void main(String[] args) {
    
    
        System.out.print("小明的期末Java成绩是:[0,100]");
        int score = 89;

        if (score < 0 || score > 100) {
    
    
            System.out.println("你的成绩是错误的");
        } else if (score >= 90 && score <= 100) {
    
    
            System.out.println("你的成绩属于优秀");
        } else if (score >= 80 && score < 90) {
    
    
            System.out.println("你的成绩属于好");
        } else if (score >= 70 && score < 80) {
    
    
            System.out.println("你的成绩属于良");
        } else if (score >= 60 && score < 70) {
    
    
            System.out.println("你的成绩属于及格");
        } else {
    
    
            System.out.println("你的成绩属于不及格");
        }
    }
}

Writing method two:

import java.util.Scanner;

public class IfElseExer4 {
    
    
    public static void main(String[] args) {
    
    
        System.out.print("小明的期末Java成绩是:[0,100]");
        int score = 89;

        if (score < 0 || score > 100) {
    
    
            System.out.println("你的成绩是错误的");
        } else if (score >= 90) {
    
    
            System.out.println("你的成绩属于优秀");
        } else if (score >= 80) {
    
    
            System.out.println("你的成绩属于好");
        } else if (score >= 70) {
    
    
            System.out.println("你的成绩属于良");
        } else if (score >= 60) {
    
    
            System.out.println("你的成绩属于及格");
        } else {
    
    
            System.out.println("你的成绩属于不及格");
        }

    }
}

Exercise 5: Write a program to declare 2 int type variables and assign values. Determine the sum of two numbers, if it is greater than or equal to 50, print 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!");
        }
    }
}

Exercise 6: Write a program to declare two double variables and assign values. Determine whether the first number is greater than 10.0 and the second number is less than 20.0, and print the sum of the two numbers. Otherwise, print the product of the two numbers.

public class IfElseExer6 {
    
    

    public static void main(String[] args) {
    
    
        double d1 = 21.2,d2 = 12.3;
        
        if(d1 > 10.0 && d2 < 20.0){
    
    
            System.out.println("两数之和为:" + (d1 + d2));
        }else{
    
    
            System.out.println("两数乘积为:" + (d1 * d2));
        }
    }

}

Exercise 7: Determine the temperature of water.

/*如果大于95℃,则打印“开水”;
如果大于70℃且小于等于95℃,则打印“热水”;
如果大于40℃且小于等于70℃,则打印“温水”;
如果小于等于40℃,则打印“凉水”。*/
public class IfElseExer7 {
    
    

    public static void main(String[] args) {
    
    
        int waterTemperature = 85;
        
        if(waterTemperature > 95){
    
    
            System.out.println("开水");
        }else if(waterTemperature > 70 && waterTemperature <= 95){
    
    
            System.out.println("热水");
        }else if(waterTemperature > 40 && waterTemperature <= 70){
    
    
            System.out.println("温水");
        }else{
    
    
            System.out.println("凉水");
        }
    }

}

2.2 switch-case selection structure

2.2.1 Basic syntax

Syntax format:

switch(表达式){
    
    
    case 常量值1:
        语句块1;
        //break;
    case 常量值2:
        语句块2;
        //break; 
    // ...
   [default:
        语句块n+1;
        break;
   ]
}

Execution flow chart:
Insert image description here
Execution process:

  • Step 1: Match each case in sequence according to the value of the expression in switch. If the value of the expression is equal to the constant value in a case, the execution statement in the corresponding case is executed.
  • Step 2: After executing the execution statement of this case
    • Case 1: If break is encountered, execute break and jump out of the current switch-case structure
    • Case 2: If no break is encountered, execution statements in other cases after the current case will continue to be executed. –> case penetration until the break keyword is encountered or all case and default execution statements are executed, and the current switch-case structure is jumped out

Notes on use:

  1. The value of the expression in switch (expression) must be one of the following types: byte, short, char, int, enumeration (jdk 5.0), String (jdk 7.0);
  2. The value in the case clause must be a constant, not a variable name or an undefined expression value or range;
  3. In the same switch statement, the constant values ​​in all case clauses are different from each other;
  4. The break statement is used to make the program jump out of the switch statement block after executing a case branch;
  5. If there is no break, the program will be executed sequentially until the end of switch;
  6. The default clause is optional. At the same time, the location is also flexible. When there is no matching case, the default statement is executed.

2.2.2 Application examples

Case 1:

public class SwitchCaseTest1 {
    
    
    public static void main(String args[]) {
    
    
        int num = 1;
		switch(num){
    
    
			case 0:
				System.out.println("zero");
				break;
			case 1:
				System.out.println("one");
				break;
			case 2:
				System.out.println("two");
				break;
			case 3:
				System.out.println("three");
				break;
			default:
				System.out.println("other");
				//break;
		}
    }
}

Case 2:

public class SwitchCaseTest2 {
    
    
    public static void main(String args[]) {
    
    
        String season = "summer";
        switch (season) {
    
    
            case "spring":
                System.out.println("春暖花开");
                break;
            case "summer":
                System.out.println("夏日炎炎");
                break;
            case "autumn":
                System.out.println("秋高气爽");
                break;
            case "winter":
                System.out.println("冬雪皑皑");
                break;
            default:
                System.out.println("季节输入有误");
                break;
        }
    }
}

Error example:

int key = 10;
switch(key){
    
    
	case key > 0 :
        System.out.println("正数");
        break;
    case key < 0:
        System.out.println("负数");
        break;
    default:
        System.out.println("零");
        break;
}

Case 3: Use switch-case to implement: For students whose scores are greater than 60 points, output 合格. If the score is less than 60, output 不合格.

class SwitchCaseTest3 {
    
    
	public static void main(String[] args) {
    
    
		int score = 67;
		/*
		写法1:极不推荐
		switch(score){
			case 0:
				System.out.println("不及格");
				break;
			case 1:
				System.out.println("不及格");
				break;
			//...

			case 60:
				System.out.println("及格");
				break;
			//...略...
		
		}
		*/

		//写法2:
		switch(score / 10){
    
    
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
				System.out.println("不及格");
				break;
			case 6:
			case 7:
			case 8:
			case 9:
			case 10:
				System.out.println("及格");
				break;
			default:
				System.out.println("输入的成绩有误");
				break;
		}

		//写法3:
		switch(score / 60){
    
    
			case 0:
				System.out.println("不及格");
				break;
			case 1:
				System.out.println("及格");
				break;
			default:
				System.out.println("输入的成绩有误");
				break;
		}
	}
}

2.2.3 Utilize the penetrability of case

In the switch statement, if break is not written after the case, there will be a penetration phenomenon, that is, once the match is successful, the value of the next case will not be judged, and it will run directly backward until a break is encountered or the entire switch statement ends. Execution terminates.

Case 4: Write a program: Enter month and day of 2023 from the keyboard, and ask to pass the program The input date is the day of the year 2023.

import java.util.Scanner;

class SwitchCaseTest4 {
    
    
	public static void main(String[] args) {
    
    
		
		Scanner scan = new Scanner(System.in);

		System.out.println("请输入2023年的month:");
		int month = scan.nextInt();

		System.out.println("请输入2023年的day:");
		int day = scan.nextInt();

		//这里就不针对month和day进行合法性的判断了,以后可以使用正则表达式进行校验。

		int sumDays = 0;//记录总天数
		
		//写法1 :不推荐(存在冗余的数据)
		/*
		switch(month){
			case 1:
				sumDays = day;
				break;
			case 2:
				sumDays = 31 + day;
				break;
			case 3:
				sumDays = 31 + 28 + day;
				break;
			//....
		
			case 12:
				//sumDays = 31 + 28 + ... + 30 + day;
				break;
		}
		*/

		//写法2:推荐
		switch(month){
    
    
			case 12:
				sumDays += 30;//这个30是代表11月份的满月天数
			case 11:
				sumDays += 31;//这个31是代表10月份的满月天数
			case 10:
				sumDays += 30;//这个30是代表9月份的满月天数
			case 9:
				sumDays += 31;//这个31是代表8月份的满月天数
			case 8:
				sumDays += 31;//这个31是代表7月份的满月天数
			case 7:
				sumDays += 30;//这个30是代表6月份的满月天数
			case 6:
				sumDays += 31;//这个31是代表5月份的满月天数
			case 5:
				sumDays += 30;//这个30是代表4月份的满月天数
			case 4:
				sumDays += 31;//这个31是代表3月份的满月天数
			case 3:
				sumDays += 28;//这个28是代表2月份的满月天数
			case 2:
				sumDays += 31;//这个31是代表1月份的满月天数
			case 1:
				sumDays += day;//这个day是代表当月的第几天
		}
		
		System.out.println(month + "月" + day + "日是2023年的第" + sumDays + "天");
        //关闭资源
		scan.close();
	}
}

expand:

/*从键盘分别输入年、月、日,判断这一天是当年的第几天
注:判断一年是否是闰年的标准:
   1)可以被4整除,但不可被100整除
	  或
   2)可以被400整除
例如:1900,2200等能被4整除,但同时能被100整除,但不能被400整除,不是闰年*/
import java.util.Scanner;

public class SwitchCaseTest04 {
    
    

    public static void main(String[] args) {
    
    

        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入year:");
        int year = scanner.nextInt();

        System.out.print("请输入month:");
        int month = scanner.nextInt();

        System.out.print("请输入day:");
        int day = scanner.nextInt();

        //判断这一天是当年的第几天==>从1月1日开始,累加到xx月xx日这一天
        //(1)[1,month-1]个月满月天数
        //(2)单独考虑2月份是否是29天(依据是看year是否是闰年)
        //(3)第month个月的day天

        //声明一个变量days,用来存储总天数
        int sumDays = 0;

        //累加[1,month-1]个月满月天数
        switch (month) {
    
    
            case 12:
                //累加的1-11月
                sumDays += 30;//这个30是代表11月份的满月天数
                //这里没有break,继续往下走
            case 11:
                //累加的1-10月
                sumDays += 31;//这个31是代表10月的满月天数
                //这里没有break,继续往下走
            case 10:
                sumDays += 30;//9月
            case 9:
                sumDays += 31;//8月
            case 8:
                sumDays += 31;//7月
            case 7:
                sumDays += 30;//6月
            case 6:
                sumDays += 31;//5月
            case 5:
                sumDays += 30;//4月
            case 4:
                sumDays += 31;//3月
            case 3:
                sumDays += 28;//2月
                //在这里考虑是否可能是29天
                if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
    
    
                    sumDays++;//多加1天
                }
            case 2:
                sumDays += 31;//1月
            case 1:
                sumDays += day;//第month月的day天
        }

        //输出结果
        System.out.println(year + "年" + month + "月" + day + "日是这一年的第" + sumDays + "天");

        scanner.close();
    }
}

Case 5: Output the corresponding season according to the specified month

import java.util.Scanner;

/*
 * 需求:指定一个月份,输出该月份对应的季节。一年有四季:
 * 		3,4,5	春季
 * 		6,7,8	夏季
 * 		9,10,11	秋季
 * 		12,1,2	冬季
 */
public class SwitchCaseTest5 {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.print("请输入月份:");
        int month = input.nextInt();

        /*
		switch(month) {
            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;
            case 8:
                System.out.println("夏季");
                break;
            case 9:
                System.out.println("秋季");
                break;
            case 10:
                System.out.println("秋季");
                break;
            case 11:
                System.out.println("秋季");
                break;
            case 12:
                System.out.println("冬季");
                break;
            default:
                System.out.println("你输入的月份有误");
                break;
		}
		*/

        // 改进版
        switch(month) {
    
    
            case 1:
            case 2:
            case 12:
                System.out.println("冬季");
                break;
            case 3:
            case 4:
            case 5:
                System.out.println("春季");
                break;
            case 6:
            case 7:
            case 8:
                System.out.println("夏季");
                break;
            case 9:
            case 10:
            case 11:
                System.out.println("秋季");
                break;
            default:
                System.out.println("你输入的月份有误");
                break;
        }

        input.close();
    }
}

Common implementation errors:

switch(month){
    
    
    case 3|4|5://3|4|5 用了位运算符,11 | 100 | 101结果是 1117
        System.out.println("春季");
        break;
    case 6|7|8://6|7|8用了位运算符,110 | 111 | 1000结果是111115
        System.out.println("夏季");
        break;
    case 9|10|11://9|10|11用了位运算符,1001 | 1010 | 1011结果是101111
        System.out.println("秋季");
        break;
    case 12|1|2://12|1|2 用了位运算符,1100 | 1 | 10 结果是1111,是15
        System.out.println("冬季");
        break;
    default:
        System.out.println("输入有误");
}

Use if-else to implement:

if ((month == 1) || (month == 2) || (month == 12)) {
    
    
    System.out.println("冬季");
} else if ((month == 3) || (month == 4) || (month == 5)) {
    
    
    System.out.println("春季");
} else if ((month == 6) || (month == 7) || (month == 8)) {
    
    
    System.out.println("夏季");
} else if ((month == 9) || (month == 10) || (month == 11)) {
    
    
    System.out.println("秋季");
} else {
    
    
    System.out.println("你输入的月份有误");
}

2.2.4 Comparison between if-else statement and switch-case statement

Conclusion: Any structure using switch-case can be converted into an if-else structure. On the contrary, it is not true.

Development experience: If you can use both switch-case and if-else, it is recommended to use switch-case. Because the efficiency is slightly higher. Detail comparison:

  • Advantages of if-else statement
    • The condition of the if statement is a Boolean value. If the conditional expression is true, it will enter the branch. It can be used for range judgment or equivalence judgment.使用范围更广 .
    • The condition of the switch statement is a constant value (byte, short, int, char, enumeration, String), which can only determine whether the result of a certain variable or expression is equal to a certain constant value, 使用场景较狭窄.
  • Advantages of switch statement
    • When the condition is to determine whether a variable or expression is equal to a fixed constant value, both if and switch can be used, and it is customary to use switch more. Because 效率稍高. When the condition is an interval judgment, only the if statement can be used.
    • Using switch can take advantage of 穿透性 to execute multiple branches at the same time, while if...else has no penetration.

case: only if-else can be used. Enter an integer from the keyboard and determine whether it is a positive number, a negative number, or zero.

import java.util.Scanner;

public class IfOrSwitchDemo {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);

        System.out.print("请输入整数:");
        int num = input.nextInt();

        if (num > 0) {
    
    
            System.out.println(num + "是正整数");
        } else if (num < 0) {
    
    
            System.out.println(num + "是负整数");
        } else {
    
    
            System.out.println(num + "是零");
        }

        input.close();
    }
}

2.2.5 Exercise

Exercise 1: Enter the integer value of the week from the keyboard and output the English word of the week

import java.util.Scanner;

public class SwitchCaseExer1 {
    
    
    public static void main(String[] args) {
    
    
        //定义指定的星期
        Scanner input = new Scanner(System.in);
        System.out.print("请输入星期值:");
        int weekday = input.nextInt();

        //switch语句实现选择
        switch(weekday) {
    
    
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("你输入的星期值有误!");
                break;
        }

        input.close();
    }
}

Exercise 2:

/*使用switch把小写类型的char型转为大写。只转换a, b, c, d, e. 其它的输出 other*/
public class SwitchCaseExer2 {
    
    

    public static void main(String[] args) {
    
    

        char word = 'c';
        switch (word) {
    
    
            case 'a':
                System.out.println("A");
                break;
            case 'b':
                System.out.println("B");
                break;
            case 'c':
                System.out.println("C");
                break;
            case 'd':
                System.out.println("D");
                break;
            case 'e':
                System.out.println("E");
                break;
            default :
                System.out.println("other");
        }
    }
}

Exercise 3:

/*编写程序:从键盘上读入一个学生成绩,存放在变量score中,根据score的值输出其对应的成绩等级:
score>=90           等级:  A
70<=score<90        等级:  B    
60<=score<70        等级:  C
score<60            等级:  D
方式一:使用if-else
方式二:使用switch-case:  score / 10:   0 - 10*/
public class SwitchCaseExer3 {
    
    

    public static void main(String[] args) {
    
    

        Scanner scan = new Scanner(System.in);
        System.out.println("请输入学生成绩:");
        int score = scan.nextInt();

        char grade;//记录学生等级
        //方式1:
//        if(score >= 90){
    
    
//            grade = 'A';
//        }else if(score >= 70 && score < 90){
    
    
//            grade = 'B';
//        }else if(score >= 60 && score < 70){
    
    
//            grade = 'C';
//        }else{
    
    
//            grade = 'D';
//        }

        //方式2:
        switch(score / 10){
    
    
            case 10:
            case 9:
                grade = 'A';
                break;
            case 8:
            case 7:
                grade = 'B';
                break;
            case 6:
                grade = 'C';
                break;
            default :
                grade = 'D';
        }

        System.out.println("学生成绩为" + score + ",对应的等级为" + grade);

        scan.close();
    }
}

Exercise 4:

/*编写一个程序,为一个给定的年份找出其对应的中国生肖。中国的生肖基于12年一个周期,每年用一个动物代表:rat、ox、tiger、rabbit、dragon、snake、horse、sheep、monkey、rooster、dog、pig。
提示:2022年:虎   2022 % 12 == 6 */
public class SwitchCaseExer4 {
    
    
    public static void main(String[] args){
    
    
        //从键盘输入一个年份
        Scanner input = new Scanner(System.in);
        System.out.print("请输入年份:");
        int year = input.nextInt();
        input.close();

        //判断
        switch(year % 12){
    
    
            case 0:
                System.out.println(year + "是猴年");
                break;
            case 1:
                System.out.println(year + "是鸡年");
                break;
            case 2:
                System.out.println(year + "是狗年");
                break;
            case 3:
                System.out.println(year + "是猪年");
                break;
            case 4:
                System.out.println(year + "是鼠年");
                break;
            case 5:
                System.out.println(year + "是牛年");
                break;
            case 6:
                System.out.println(year + "是虎年");
                break;
            case 7:
                System.out.println(year + "是兔年");
                break;
            case 8:
                System.out.println(year + "是龙年");
                break;
            case 9:
                System.out.println(year + "是蛇年");
                break;
            case 10:
                System.out.println(year + "是马年");
                break;
            case 11:
                System.out.println(year + "是羊年");
                break;
            default:
                System.out.println(year + "输入错误");
        }
    }
}

Exercise 5: Betting Game

/*随机产生3个1-6的整数,如果三个数相等,那么称为“豹子”,如果三个数之和大于9,称为“大”,如果三个数之和小于等于9,称为“小”,用户从键盘输入押的是“豹子”、“大”、“小”,并判断是否猜对了

提示:随机数  Math.random()产生 [0,1)范围内的小数
     如何获取[a,b]范围内的随机整数呢?(int)(Math.random() * (b - a + 1)) + a*/
```java
import java.util.Scanner;

public class SwitchCaseExer5 {
    
    
    public static void main(String[] args) {
    
    
        //1、随机产生3个1-6的整数
        int a = (int)(Math.random()*6 + 1);
        int b = (int)(Math.random()*6 + 1);
        int c = (int)(Math.random()*6 + 1);

        //2、押宝
        Scanner input = new Scanner(System.in);
        System.out.print("请押宝(豹子、大、小):");
        String ya = input.next();
        input.close();

        //3、判断结果
        boolean result = false;
        //switch支持String类型
        switch (ya){
    
    
            case "豹子": result = a == b && b == c; break;
            case "大": result = a + b + c > 9; break;
            case "小": result = a + b + c <= 9; break;
            default:System.out.println("输入有误!");
        }

        System.out.println("a,b,c分别是:" + a +"," + b +"," + c );
        System.out.println(result ? "猜中了" : "猜错了");
    }
}

Exercise 6:

使用switch语句改写下列if语句:

int a = 3;
int x = 100;
if(a==1)
	x+=5;
else if(a==2)
	x+=10;
else if(a==3)
	x+=16;
else
	x+=34;
int a = 3;
int x = 100;

switch(a){
    
    
    case 1:
        x += 5;
        break;
    case 2:
        x += 10;
        break;
    case 3:
        x += 16;
        break;
    default :
        x += 34;

}

This concludes today’s study. The author declares here that the author writes articles only for learning and communication, so that more readers who learn Java language can avoid detours and save time. It is not used for other purposes. If there is any infringement, Just contact the blogger to delete it. Thank you for reading this blog post. I hope this article can be a guide on your programming journey. Happy reading!


Insert image description here

    I never get tired of reading a good book a hundred times, and I will know myself after reading the lessons thoroughly. And if I want to be the most handsome guy in the room, I must persist in acquiring more knowledge through learning, use knowledge to change my destiny, use my blog to witness my growth, and use my actions to prove that I am working hard.
    If my blog is helpful to you, if you like my blog content, please 点赞, 评论, 收藏 me!
 Coding is not easy, and everyone’s support is what keeps me going. Don’t forget to like Three consecutive hits with one click! I heard that those who like it will not have bad luck and will be full of energy every day! If you really want to have sex for nothing, then I wish you a happy day every day, and you are welcome to visit my blog often. 关注

Guess you like

Origin blog.csdn.net/xw1680/article/details/134306860