Java Basics (03): process control statements, and algorithm applications

Source code of this article: GitHub · click here | gitee · click here

1、 Branch statement

Process control statements are very important to any programming language. Java is based on the different steps and code blocks executed by the process control program.

1. If condition

If conditional statements will execute different statements according to different judgment conditions. Whether the conditions in parentheses after if are valid is a key step. The judgment result of if conditions must be true or false. IF... Else statement executes the corresponding code block if the if condition is met, otherwise it executes the elase code block.

public class Process01 {
    public static void main(String[] args) {
        // 演示:Node01
        if (compare01(40,30)){
            System.out.println("40>30:true");
        } else {
            System.out.println("40>30:false");
        }
        // 演示:Node02
        if (compare01(10,20) && compare01(20,30)){
            System.out.println("条件成立");
        } else {
            System.out.println("条件不成立");
        }
        // 演示:Node03
        if (compare01(20,10) || compare01(20,30)){
            System.out.println("条件成立");
        } else {
            System.out.println("条件不成立");
        }
        // 演示:Node04
        if(compare02(1,1))
            if(compare02(2,2))
                System.out.println("Running...");
        // 演示:Node05
        if(compare01(1,2))
            if(compare01(5,3)){
                System.out.println("5>3");
            }
    }

    private static boolean compare01 (int num1,int num2){
        System.out.println("判断:num1="+num1+";num2="+num2);
        return num1 > num2 ;
    }
    private static boolean compare02 (int num1,int num2){
        System.out.println("判断:num1="+num1+";num2="+num2);
        return num1 == num2 ;
    }
}

Node case, test result description:

Note: braces must be used in process control statements, even if there is only one line of code. Single line coding is avoided, which is the basic specification. In the above test nodes 4 and 5, the code feels heartbreaking when looking at it.

2. If else if condition

Else... The if branch statement is used for judgment processing in many cases until the branch judgment condition is successful and the branch module code is executed. If there is no else condition, all branches can be ended directly without meeting the else condition.

public class Process02 {
    public static void main(String[] args) {
        elseIf(11) ;
        elseIf(9) ;
        elseIf(5);
    }

    private static void elseIf (Integer num){
        if (num > 10){
            System.out.println("num > 10");
        } else if (num > 7){
            System.out.println("num > 7");
        } else if (num > 4){
            System.out.println("num > 4");
        } else {
            System.out.println("num < 4");
        }
    }
}

Note: judge one by one according to the conditions until the first satisfied condition is found. It will not continue to execute the following judgment. After the execution of the branch statement, it will exit the current else If process. The logic judgment code of more than three layers can be implemented by guard statement, policy mode, state mode, etc.

3. Switch condition

Process Description: the switch statement first obtains the value of the expression and determines whether the value of the expression is the same as the constant value after the case statement. If the matching is successful, the code block after the case is executed until the break statement is encountered. If the break interrupt is missing, continue to match the next case constant until the break is encountered. If none of the conditions match, the statement after default is executed. The default statement is optional. If there is no default statement, the constant values of case in the same switch statement must be different from each other.

public class Process03 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(system.in);
        System.out.print("What day is it today:");
        String value = scan.next();
        weekInfo(value);
    }

    private static void weekInfo (String value){
        switch (value) {
            case "Monday":
                System.out.println("Monday");
                break;
            case "Tuesday":
                System.out.println("Tuesday");
                break;
            case "Wednesday":
                System.out.println("Wednesday");
                break;
            case "Thursday":
                System.out.println("Thursday");
                break;
            case "Friday":
                System.out.println("Friday");
                break;
            case "Saturday":
                System.out.println("Saturday");
                break;
            case "Sunday":
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Matching failure");
                break;
        }
    }
}

Note: from jdk1 After 7, switch supports string matching.

2、 Circular statement

A circular statement is to repeatedly execute the same operation when certain conditions are met. Loop statements include: for loop, while loop and do ··· while loop.

1. For loop

The most useful loop method in java development is also the basic control statement in many algorithms. In the coding and implementation of many common algorithms, the for loop method needs to be used.

public class Process04 {
    public static void main(String[] args) {
        // Node01
        int sum = 0;
        for(int i=1; i<=100; i++) {
            sum += i;
        }
        System.out.println(sum);

        // Node02
        String[] nameArr = {"Java","C++","C#"} ;
        for (String name:nameArr){
            System.out.println("name="+name);
        }

        // Node03
        // 输出 i = 13
        int i = 0;
        for (i++; i++ < 10; i++);
        System.out.println(++i);

        // 输出:j=3 6 9
        int j = 0;
        for (j++; j++ < 10; j++){
            System.out.println(++j);
        }
    }
}

Node case, test result description:

Note: the more basic things are, the more difficult it is to learn. As the basic control of many algorithms, the for statement is quite complicated to understand.

2. While loop

The while loop statement first judges whether the condition is true before executing the loop body;

The do ··· while loop statement executes the loop body once, and then determines whether the condition is true, so do ·· while will be executed at least once;

public class Process05 {
    public static void main(String[] args) {
        int num1 = 1;
        int num2 = 1;

        // while循环
        while(num1 <= 3) {
            System.out.println("num1 == " + num1);
            num1++;
        }

        // do...while循环
        do {
            System.out.println("num2 == " + num2);
            num2++;
        } while(num2 <= 3);
    }
}

Note: while loop is not used much in actual development because it is very easy to cause dead loop.

3、 Process interruption

There are three kinds of process interruption statements in Java. The keywords are break, continue and return statements.

1. Return statement

The most commonly used process control keyword in Java. After executing the return statement, it returns from the method and returns to the business process calling the method.

public class Process06 {
    public static void main(String[] args) {
        System.out.println(getNum1());
        System.out.println(getNum2());
    }
    public static int getNum1 (){
        int a =100;
        try{
            return a+1;   // 这里是运算逻辑,非赋值
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            return a;
        }
    }
    public static int getNum2 (){
        int a =100;
        try{
            return a++;   //  a++ -> a=a+1 此时a的值改变
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            return a;
        }
    }
}

Return always in position

2. Break statement

Break break statements are often used in for, while and do ··· while loops to exit the current whole loop process, not the current loop.

public class Process07 {
    public static void main(String[] args) {
        for (int i = 1 ; i < 3 ; i++){
            if (i == 2){
                break ;
            }
            System.out.println("i = " + i);
        }
    }
}

3. Continue statement

Continue interrupt statements are often used in for, while and do ··· while loops to exit the current loop and enter the next loop.

public class Process08 {
    public static void main(String[] args) {
        for (int i = 1 ; i < 3 ; i++){
            if (i == 1){
                continue ;
            }
            System.out.println("i = " + i);
        }
    }
}

4、 Application scenario

1. Bubble sorting algorithm

public class Process09 {
    public static void main(String[] args) {
        int[] score = {9,8,7,6,5} ;
        // 排序次数:最多 length - 1 次
        for (int i = 0 ; i < score.length -1 ; i ++){
            // 当前排序的集合区间,排序完一个数据就放弃一个
            for (int j = 0 ; j < score.length - i - 1 ; j++){
                // 冒泡排序:把结果大的向后扔
                if (score[j] > score[j+1]){
                    int temp = score[j] ;
                    score[j] = score[j+1] ;
                    score[j+1] = temp ;
                }
            }
        }
        // 输出排序后的结果集
        for (int i = 0 ; i < score.length ; i++){
            System.out.print(score[i]);
        }
    }
}

2. Permutation and combination algorithm

There are 1, 2, 3 and 4 numbers. How many different three digits can be formed without repeated numbers? How much is it?

public class Process10 {
    public static void main(String[] args) {
        arrange() ;
    }
    public static void arrange (){
        int i=0; // 百位数
        int j=0; // 十位数
        int k=0; // 个位数
        int t=0; // 计数器
        for (i = 1 ; i <= 4 ; i++){
            for (j = 1 ; j <= 4 ; j++){
                for (k = 1 ; k <=4 ; k++){
                    if (i != j && j != k && k != i){
                        t += 1 ;
                        System.out.print(i*100+j*10+k+"--");
                    }
                }
            }
        }
        System.out.println();
        System.out.println("t="+t);
    }
}

3. Common recursive algorithms

Implementation of various calculation methods based on recursive idea.

public class Process11 {
    public static void main(String[] args) {
        System.out.println(getSumOne(100));
        System.out.println(getSumTwo(30));
        System.out.println(getSumThree(5));
    }
    /**
     * 使用递归的方式计算1+2+...+100
     */
    public static int getSumOne (int i){ // 传入100
        int sum ;
        if (i == 1){
            return 1 ;
        }
        else {
            sum = i + getSumOne(i - 1) ;
        }
        return sum ;
    }
    /**
     * 一列数的规则如下: 1、1、2、3、5、8、13、21、34...
     * 求第30位数是多少, 用递归算法实现
     */
    public static int getSumTwo (int i){ // 传入第几位数下标
        if (i <= 0){
            return 0 ;
        } else if (i == 1 || i == 2){ // 处理前面2位的1,1
            return 1 ;
        } else { // 当前位数是前两位之和
            return getSumTwo(i - 1) + getSumTwo(i - 2) ;
        }
    }
    /**
     * 1*2*3*...*100 递归计算阶乘
     */
    public static int getSumThree (int i){
        if (i == 1){
            return i ;
        } else {
            return i * getSumThree (i - 1) ;
        }
    }
}

5、 Source code address

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent

Recommended reading: Java Foundation Series

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>