Java small test chopper - program logic control

1 Introduction

  • In this blog, let’s learn about the program logic control in Java, including sequence structure, branch structure, loop structure, etc. If you have the foundation of C language, I believe it is not difficult for you to learn this part, because the difference is not very big

2. Sequential structure

  • The sequential structure is executed line by line according to the written code.
  • Get up at 8:00 in the morning ---> Wash ---> Eat breakfast ---> Work ---> Eat lunch ---> Go to class ---> Work ---> After dinner ---> Play with your phone --->Sleeping Everyday life seems to be so regular, doing everything sequentially, the future is bleak~~~.
System.out.println("aaa");
System.out.println("bbb");
System.out.println("ccc");
// 运行结果
aaa
bbb
ccc
  • If the writing order of the code is adjusted, the execution order will also change, as shown in the following code:
System.out.println("aaa");
System.out.println("ccc");
System.out.println("bbb");
// 运行结果
aaa
ccc
bbb

3. Branch structure

3.1 if statement

3.1.1 Grammar format 1

  • If the result of the Boolean expression is true, execute the statement in the if, otherwise execute the statement in the else.
if(布尔表达式){
// 语句1
}else{
// 语句2
}
  • For example: Xiao Ming, if you get a score of 90 or above in this test, I will reward you with a chicken leg. 
int score = 92;
if(score >= 90){
System.out.println("吃个大鸡腿!!!");
}

Note : Different from the C language, in Java, if () brackets must be filled with Boolean expressions , codes like if (1) cannot be run.

3.1.2 Grammar format 2

  • If the result of the Boolean expression is true, execute the statement in the if, otherwise execute the statement in the else.
if(布尔表达式){
// 语句1
}else{
// 语句2
}
  • For example: Xiao Ming, if you get more than 90 points in this test, I will reward you with a big chicken drumstick, otherwise you will get nothing.
int score = 92;
if(score >= 90){
System.out.println("吃个大鸡腿!!!");
}else{
System.out.println("啥也没有!!!");
}

3.1.3 Syntax format 3

  • If expression 1 is true, statement 1 is executed, otherwise expression 2 is true, statement 2 is executed, otherwise statement 3 is executed.
if(布尔表达式1){
// 语句1
}else if(布尔表达式2){
// 语句2
}else{
// 语句3
}

For example: taking into account the self-esteem of students, the score ranking is not disclosed, so:
the score between [90, 100] is excellent, the
score is before [80, 90), and the good
score is between [70, 80), For medium
grades between [60, 70), for passing
grades between [0, 60), for failing grades Wrong
data
Notify students of grades according to the above method.

if(score >= 90){
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 if(score >= 0 && score < 60){
System.out.println("不及格");
}else{
System.out.println("错误数据");
}
  • If you have learned the if statement in C, then the if statement in Java must not bother you, just pay special attention: if (Boolean expression), the value stored in () is a Boolean expression .

3.1.4 The semicolon problem

int x = 20;
if (x == 10);
{
System.out.println("hehe");
}
// 运行结果
hehe
  • An extra semicolon is written here, causing the semicolon to become the statement body of the if statement, and the code in { } has become a code block that has nothing to do with an if .

3.1.5 Dangling else problem

int x = 10;
int y = 10;
if (x == 10)
if (y == 10)
System.out.println("aaa");
else
System.out.println("bbb");
  • Braces are not required in the if / else statement. But you can also write a statement (you can only write one statement). At this time, else matches the closest if, but it is not recommended to write this way in actual development. It is better to add curly braces , making the code more readable.

3.2 switch statement

3.2.1 Basic syntax

switch(表达式){
    case 常量值1:{
        语句1;
        [break;]
    }
    case 常量值2:{
        语句2;
        [break;]
    }
        ...
    default:{
    内容都不满足时执行语句;
    [break;]
    }
}

3.2.2 Execution process

  1. The value of the expression is evaluated first.
  2. Comparing with case in turn, once there is a corresponding match, the statement under this item will be executed until a break is encountered.
  3. default is executed when the value of the expression does not match the listed items.
  • Code example: Output the day of the week according to the value of day.
  • int day = 1;
    switch(day) {
        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;
    }

    【Notice】

  • Constant values ​​behind multiple cases cannot be repeated.
  • The parentheses of the switch can only contain expressions of the following types:
      basic types: byte, char, short, int,
    and note that it cannot be of the long type.
      Reference type: String constant string, enumeration type.
double num = 1.0;
switch(num) {
    case 1.0:
      System.out.println("hehe");
      break;
    case 2.0:
      System.out.println("haha");
      break;
}
// 编译出错
Test.java:4: 错误: 不兼容的类型: 从double转换到int可能会有损失
switch(num) {
^
1 个错误
  • Do not omit break, otherwise the effect of "multi-branch selection" will be lost, as in the following code, if the first case1 has no break, then
int day = 1;
switch(day) {
    case 1:
      System.out.println("星期一");
      // break;
    case 2:
      System.out.println("星期二");
      break;
}
// 运行结果
星期一
星期二
  • switch cannot express too complex conditions, complex conditions can be expressed with if.
// 例如: 如果 num 的值在 10 到 20 之间, 就打印 hehe
// 这样的代码使用 if 很容易表达, 但是使用 switch 就无法表示.
if (num > 10 && num < 20) {
System.out.println("hehe");
}
  • Although switch supports nesting, it is ugly and generally not recommended.
int x = 1;
int y = 1;
    switch(x) {
      case 1:
        switch(y) {
          case 1:
            System.out.println("hehe");
            break;
        }
          break;
      case 2:
        System.out.println("haha");
        break;
    }
  • The beauty of the code is also an important criterion. After all, this is a world of face.

  • To sum up: we found that the use of switch is relatively limited.

4. Cycle structure

4.1 while loop

4.1.1 Basic grammar format

  • while(), the type in () is Boolean expression type , and the loop condition is true, then execute the loop statement; otherwise end the loop
while(循环条件){
循环语句;
}
  •  Code Example: Calculate the factorial of 5
int n = 1;
int result = 1;
while (n <= 5) {
    result *= n;
    n++;
}
System.out.println(num);
// 执行结果
120
  • Code Example 4: Calculate 1! + 2! + 3! + 4! + 5!
int num = 1;
int sum = 0;
// 外层循环负责求阶乘的和
while (num <= 5) {
    int factorResult = 1;
    int tmp = 1;
    // 里层循环负责完成求阶乘的细节.
while (tmp <= num) {
    factorResult *= tmp;
    tmp++;
}
sum += factorResult;
num++;
}
System.out.println("sum = " + sum);
  • Here we find that when a code has multiple loops, the complexity of the code is greatly increased. And more complex codes are more error-prone, and we will use simpler methods to solve this problem later.

【Notice】

  1. Similar to if, the statement below while can not write { }, but only one statement can be supported when it is not written. It is recommended to add {}.
  2. Similar to if, the { after while is suggested to be written on the same line as while.
  3. Similar to if, do not write more semicolons after while , otherwise the loop may not be executed correctly.
int num = 1;
while (num <= 10); {
    System.out.println(num);
    num++;
}
// 执行结果
[无任何输出, 程序死循环]
  • At this time, is the statement body of while (this is an empty statement), and the actual { } part has nothing to do with the loop. At this time, the loop condition num <= 10 is always true, resulting in an infinite loop of the code.

4.2 break

  •  The function of break is to end all loops ahead of time and jump out of the loop body directly.
  • Code Example: Find the first multiple of 3 from 100 - 200.
int num = 100;
while (num <= 200) {
    if (num % 3 == 0) {
        System.out.println("找到了 3 的倍数, 为:" + num);
        break;
    }
num++;
}
// 执行结果
找到了 3 的倍数, 为:102
  • After the if condition is met, print num, break, and jump out of the while loop, so only one 102 is found.

4.3 continue

  • The function of continue is to skip this cycle and immediately enter the next cycle.
  • Code Example: Find all multiples of 3 from 100 - 200.
int num = 100;
while (num <= 200) {
    if (num % 3 != 0) {
    num++; // 这里的 ++ 不要忘记! 否则会死循环.
    continue;
    }
System.out.println("找到了 3 的倍数, 为:" + num);
num++;
}
  • When the continue statement is executed, the content after this loop will not be executed, and it will immediately enter the next loop (determine the loop condition) , so that the print statement below will not be executed. 

4.4 for loop

4.4.1 Basic syntax

        for(expression①;Boolean expression②;expression③){         expression④;         }

  • Expression 1: It is used to initialize the initial value setting of the loop variable, and it is executed at the very beginning of the loop, and it is executed only once.
  • Expression 2: Loop condition, the loop continues if it is full, otherwise the loop ends.
  • Expression 3: The loop variable update method.

4.4.2 Execution process

①②③④--->②③④--->②③④--->②③④--->②③④--->②③④--->...--->② is false, and the loop ends.

4.4.3 Code example

  • Calculate 1! + 2! + 3! + 4! + 5!
int sum = 0;
for (int i = 1; i <= 5; i++) {
    int tmp = 1;
    for (int j = 1; j <= i; j++) {
        tmp *= j;
    }
    sum += tmp;
}
System.out.println("sum = " + sum);

4.4.4 Precautions

  1. Similar to if, the statement below for can not write { }, but only one statement can be supported when it is not written, it is recommended to add { }
  2. Similar to if, the { after for is suggested to be written on the same line as while.
  3. Similar to if, do not write more semicolons after for, otherwise the loop may not be executed correctly.
  4. Like the while loop, use continue to end a single loop, and break to end the entire loop.

4.5 do while loop

4.5.1 Basic syntax

  • The loop statement is executed first, and then the loop condition is determined. If the loop condition is met, the execution continues, otherwise the loop ends.
do{
    循环语句;
}while(循环条件);

 4.5.2 Code example

  • print 1 - 10
    int num = 1;
    do {
        System.out.println(num);
        num++;
    } while (num <= 10);

4.5.3 Precautions

  1. Do not forget the semicolon at the end of the do while loop.
  2. Generally, do while is rarely used, and for and while are more recommended.

5 Conclusion

This blog mainly introduces the program logic control related content in Java, and mainly introduces the sequence structure, branch structure and loop structure. I believe that if you have the relevant grammatical foundation of C language, the content of this part will not be difficult for you. I hope you will continue to pay attention to me!

Guess you like

Origin blog.csdn.net/weixin_44580000/article/details/124420804