First knowledge of Java -- logical control structure in Java

Posted by alex_bg on Sun, 27 Feb 2022 00:08:25 +0100

catalogue

1, Sequential structure

2, Branching structure

πŸ“ if statement

πŸ“ switch statement

3, Cyclic structure

πŸ“ while loop

πŸ“break

πŸ“continue

πŸ“ for loop

πŸ“ do...while() loop

4, Input and output in Java

πŸ“ Output to console

πŸ“ Format character

πŸ“ Input from keyboard

V. summary

πŸš† Brief description:

  • Because the content introduced in this article is similar to the branch structure and loop structure in C language, some contents will not be described in detail.
  • If you don't know much about the logical structure in C language, you can take a look at the logical structure of C language I wrote.

πŸš€ C language logical structure content navigation:

C language branch structure

C language loop structure

In this article, the use of logical structures in Java and the contents that need attention will be introduced in detail.

1, Sequential structure

The sequence structure is relatively simple, and the code is executed line by line according to the writing order. The execution order of the program is related to the writing order of the code.

public class TestDemo2 {
    public static void main(String[] args) {
        System.out.println("hello");
        System.out.println("world");
        System.out.println("Java");
    }
}

2, Branching structure

πŸ“ if statement

πŸŒ€ Single branch

if(Boolean expression){
    //Execute code when conditions are met
}

πŸŒ€ Double branch

if(Boolean expression){
    //Execute code when conditions are met
}else{
    //Execute code when conditions are not met
}

πŸŒ€ Multi branch

if(Boolean expression){
    //Execute code when conditions are met
}else if(Boolean expression){
    //Execute code when conditions are met
}else{
    //Execute code when none of the conditions are met
}

πŸŽ„ Exercise 1: judge whether a number is odd or even

public class TestDemo2 {
    public static void main(String[] args) {
        int num = 10;
        if (0 == num % 2) {
            System.out.println("even numbers");
        } else {
            System.out.println("Odd number");
        }
    }
}

πŸŽ„ Exercise 2: judge whether a number is positive or negative

public class TestDemo2 {
    public static void main(String[] args) {
        int num = -10;
        if (num > 0) {
            System.out.println("num Is a positive number");
        } else if (num < 0) {
            System.out.println("num Is a negative number");
        } else {
            System.out.println("num Is 0");
        }
    }
}

πŸŽ„ Exercise 3: determine whether a year is a leap year

  • Ordinary leap year: if the Gregorian calendar year is a multiple of 4 and not a multiple of 100, it is a leap year (for example, 2004 and 2020 are leap years).
  • Century leap year: the Gregorian calendar year is a whole hundred, and it must be a multiple of 400 to be a leap year (for example, 1900 is not a leap year, and 2000 is a leap year).

πŸ’¦ Code 1:

public class TestDemo2 {
    public static void main(String[] args) {
        int year = 2022;
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            System.out.println(year + "It's a leap year");
        } else {
            System.out.println(year + "Not a leap year");
        }
    }
}

πŸ’¦ Code 2:

public class TestDemo2 {
    public static void main(String[] args) {
        int year = 2000;
        if (year % 100 == 0) {
            //Judge century leap year
            if (year % 400 == 0) {
                System.out.println(year + "It's a leap year of the century");
            } else {
                System.out.println(year + "Not a leap year");
            }
        } else {
            if (year % 4 == 0) {
                //Judge ordinary leap year
                System.out.println(year + "It's an ordinary leap year");
            } else {
                System.out.println(year + "Not a leap year");
            }
        }
    }

}

Operation results

πŸ’₯ Note 1: suspension else problem

public class TestDemo2 {
    public static void main(String[] args) {
               int x = 10;
        int y = 10;
        if (x == 10)
            if (y == 20)
                System.out.println("aaa");
       else
                System.out.println("bbb");
    }

}

Operation results

🌊 if ... Curly braces may not be used in else statements, but only one statement can be written. At this point else matches the closest if.

✨ Suggestion: don't omit parentheses when writing code.

πŸ’₯ Note: style code 2

int x = 10;
if (x == 10) {
    // Meet the conditions
} else {
    // Conditions not met
}

πŸ‘€ The code style in Java is different from that in C language.

πŸ’₯ Note 3: semicolon problem

public class TestDemo2 {
    public static void main(String[] args) {
        int x = 20;
        if (x == 10) ; {
            System.out.println("hehe");
        }
    }
}

Operation results

✨ A semicolon is written after the if, resulting in the semicolon becoming the statement body of the if statement, and the code in {} has become a code block irrelevant to an if

πŸ“ switch statement

Basic grammar

    switch(integer|enumeration|character|character string){
        case Content 1 : {
            Execute statement when content is satisfied;
        [break;]
        }
        case Content 2 : {
            Execute statement when content is satisfied;
        [break;]
        }
        ...
        default:{
            Execute the statement when the content is not satisfied;
        [break;]
        }
    }

πŸŽ„ Exercise: output the week based on the value of day

public class TestDemo2 {
    public static void main(String[] args) {
        int day = 1;
        switch (day) {
            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("Parameter mismatch");
                break;
        }
    }
}
  • According to the different values of switch, the corresponding case statement will be executed The case statement will end when a break is encountered
  • If the value in switch has no matching case, the statement in default will be executed
  • It is recommended that a switch statement should be accompanied by default.

πŸ’₯ Note 1: do not omit break, otherwise the effect of "multi branch selection" will be lost.

public class TestDemo2 {
    public static void main(String[] args) {
        int day = 1;
        switch (day) {
            case 1:
                System.out.println("Monday");
            case 2:
                System.out.println("Tuesday");
                break;
        }
    }

}

Operation results

πŸ‰ If you do not write break, the case statements will be executed down in turn, thus losing the effect of multiple branches.

πŸ’₯ Note 2:

  • The value in switch can only be integer | enumeration | character | string.
  • JDK1.5 start to introduce enumeration: enumeration can also be used as a switch parameter.
public class TestDemo2 {
    public static void main(String[] args) {
        double num = 1.0;
        switch (num) {
            case 1.0:
                System.out.println("hehe");
                break;
            case 2.0:
                System.out.println("haha");
                break;
        }
    }
}

⭐ Use string as switch parameter

public class TestDemo2 {
    public static void main(String[] args) {
        String str = "hello";
        switch (str) {
            case "abc":
                System.out.println(1);
                break;
            case "hello":
                System.out.println(2);
                break;
            default:
                System.out.println("error");
        }
    }
}

Operation results

πŸ’₯ Note 3: switch cannot express complex conditions

// For example, if the value of num is between 10 and 20, print hehe
// Such code is easy to express using if, but it cannot be expressed using switch
if (num > 10 && num < 20) {
        System.out.println("hehe");
    }

πŸ’₯ Note 4: Although switch supports nesting, it is ugly~

public class TestDemo2 {
    public static void main(String[] args) {
        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;
        }
    }
}

πŸ’¦ Combined with the above features, the use of switch has great limitations.

✨ What are the data types that cannot be used as switch parameters in Java?

  • long,float,double,boolean

3, Cyclic structure

πŸ“ while loop

Basic syntax format:

while(Cycle condition(Boolean expression)){
    Circular statement;
}

✨ When the loop condition is true, execute the loop statement; Otherwise, end the cycle.

πŸŽ„ Exercise 1: print numbers 1 - 10

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 10) {
            System.out.println(i);
            i++;
        }
    }
}

πŸŽ„ Exercise 2: calculate the sum of 1 to 100

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

πŸŽ„ Exercise 3: calculate the factorial of 5

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 1;
        int temp = 1;
        while (i <= 5) {
            temp *= i;
            i++;
        }
        System.out.println(temp);
    }
}

πŸŽ„ Exercise 4: calculate the sum of factorials from 1 to 5

public class TestDemo2 {
    public static void main(String[] args) {
        int num = 1;
        int sum = 0;
        // The outer loop is responsible for finding the sum of factorials
        while (num <= 5) {
            int ret = 1;
            int tmp = 1;
            // The inner loop is responsible for factoring each number
            while (tmp <= num) {
                ret *= tmp;
                tmp++;
            }
            sum += ret;
            num++;
        }
        System.out.println("sum = " + sum);
    }
}

πŸ’₯ matters needing attention

  • Similar to if, the statement under while can not write {}, but only one statement can be supported when it is not written It is suggested to add {}
  • Similar to if, the {suggestion after while is written on the same line as while
  • Similar to if, do not write semicolon after while, otherwise the loop may not execute correctly
public class TestDemo2 {
    public static void main(String[] args) {
        int num = 1;
        while (num <= 10) ;
        {
            System.out.println(num);
            num++;
        }
    }
}

In this code; (semicolon) is a loop statement with while (this is an empty statement), and the actual {} part is independent of the loop. At this time, the loop condition num < = 10 is always true, resulting in an endless loop of code.

πŸ“break

✨ The function of break is to end the cycle ahead of time.
πŸŽ„ Exercise: output multiples of the first 3 of 100 to 200.

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 100;
        while (i <= 200) {
            if (i % 3 == 0) {
                System.out.println("Found the first multiple of 3" + i);
                break;
            }
            i++;
        }
    }
}

⭐ The loop ends when break is executed in the loop.

πŸ“continue

✨ The function of continue is to skip this cycle and immediately enter the next cycle.

πŸŽ„ Exercise: output multiples of all 3 in 100 - 200.

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 100;
        while (i <= 200) {
            if (i % 3 != 0) {
                i++;
                continue;
            }
            System.out.println("3 Multiple of" + i);
            i++;
        }
    }
}

⭐ When the continue statement is executed in the loop, it will immediately enter the next loop (determine the loop conditions), so it will not execute the following print statement.

πŸ’₯ matters needing attention:

  • Both break and continue must be used in the loop. Special: break can be used in switch.
  • If it is a multiple loop, break can only jump out of the loop closest to it.

πŸ“ for loop

Basic grammar

for(Expression 1;Expression 2(Boolean expression);Expression 3){
    Circulatory body;
}

πŸš€ explain:

  • Expression 1: used to initialize loop variables
  • Expression 2: loop condition
  • Expression 3: update loop variable

🌊 Compared with the while loop, the for loop combines these three parts together and is not easy to miss when writing code

πŸŽ„ Exercise: calculate 1+ 2! + 3! + 4! + 5!

public class TestDemo2 {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            int temp = 1;
            for (int j = 1; j <= i; j++) {
                temp *= j;
            }
            sum += temp;
        }
        System.out.println(sum);
    }
}

πŸ’₯ Precautions (similar to while loop)

  • Similar to if, the statement below for can not write {}, but only one statement can be supported when it is not written It is suggested to add {}
  • Similar to if, the {suggestion after for is written on the same line as while
  • Similar to if, do not write more semicolons after for, otherwise the loop may not execute correctly

πŸ“ do...while() loop

Basic grammar

do{
    Circular statement;
}while(Cycle condition(Boolean expression));

πŸŽ„ Exercise: printing 1 ~ 10

public class TestDemo2 {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println(i);
            i++;
        } while (i <= 10);
    }
}

πŸ’₯ matters needing attention:

  1.  do... Don't forget the semicolon at the end of the while loop
  2. General do While is rarely used. for and while are recommended
  3. do... The while loop will be executed at least once

4, Input and output in Java

The output statement has been seen in the previous code. Here is a brief summary.

πŸ“ Output to console

Basic grammar

System.out.println("Output and wrap"); // Output a string with newline
System.out.print("Output does not wrap"); // Output a string without line breaks
System.out.printf("%d\n",10); // Format output

πŸš€ explain:

  • println output content comes with \ n, print does not come with \ n
  • The format output mode of printf is basically the same as that of C language

🌌 Example:

public class TestDemo {
    public static void main(String[] args) {
        System.out.println("Hello World");
        int x = 10;
        System.out.printf("x=%d\n",x);
    }
}

Operation results

πŸ“ Format character

πŸ“ Input from keyboard

Read in one character (understand)

  • Directly use system in. Read can read in one character However, it needs to be combined with exception handling (the contents of exceptions will be discussed in the later article)

🌌 Example:

import java.io.IOException; // IOException package needs to be imported

public class TestDemo {
    public static void main(String[] args) throws IOException {
        System.out.print("Enter a Char:");
        char i = (char) System.in.read();
        System.out.println("your char is :" + i);
    }

}

Operation results

This method is troublesome. Just understand it.

πŸ“ Using Scanner to read string / integer / floating point number in Java

  • To use scanner, you need to import the package: import Java util. Scanner;
  • Scanner sc = new Scanner(System.in); System.in: read data from the keyboard

🌌 Example:

import java.util.Scanner;// The util package needs to be imported

public class TestDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter name:");
        String name = sc.next();
        System.out.print("Enter age:");
        int age = sc.nextInt();
        System.out.print("Enter grade:");
        float score = sc.nextFloat();
        System.out.println("full name:" + name + "\n Age:" + age + "\n Achievements:" + score);
        sc.close(); // Note that remember to call the close method
    }

}

Operation results

✨ next() ends when it encounters a space when reading the string, and nextLine() will read the space character

🌌 Example: next();

import java.util.Scanner;// The util package needs to be imported

public class TestDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.next();
        System.out.println(str1);
    }
}

Operation results

🌌 Example: nextLine();

import java.util.Scanner;// The util package needs to be imported

public class TestDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.nextLine();
        System.out.println(str1);
    }

}

Operation results

πŸ’₯ matters needing attention:

  • Input integer: nextInt(); Output string: next(); Or nextLine();
  • nextInt(); Cannot be placed in next(); Or nextLine(); Used before.
  • sc.close(); In Java, it is considered that Scanner is equivalent to a file. It will be opened when it is used and closed when it is used. Generally, close () is not added; It doesn't affect.

πŸŽ„ Use Scanner loop to read N numbers

import java.util.Scanner;// The util package needs to be imported

public class TestDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = 0;
        double sum = 0.0;
        while (sc.hasNextDouble()) {
            double ret = sc.nextDouble();
            sum += ret;
            num++;
        }
        System.out.println(sum);
        sc.close();
    }
}

Operation results

🌊 The return value of hasNextDouble() is of type boolean.

πŸ’₯ matters needing attention:

  • When multiple data are input circularly, ctrl + D is used in IDEA to end the circular input.

πŸŽ„ Exercise: number guessing game

import java.util.Random;//To use Random, you need to guide the package
import java.util.Scanner;// The util package needs to be imported

public class TestDemo {
    public static void main(String[] args) {
        Random random = new Random();
        int ran = random.nextInt(100) + 1;
        //Random numbers generated by random are left closed and right open intervals. Entering 100 is actually 0 to 99 -- > [0 ~ 100], and if + 1 is 1 ~ 100 [1 ~ 101)
        System.out.println("Please enter the number you want to guess");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            int num = scanner.nextInt();
            if (num > ran) {
                System.out.println("Your guess is too big");
            } else if (num < ran) {
                System.out.println("Your guess is too small");
            } else {
                System.out.println("Congratulations, you guessed right");
                break; //If you guess right, jump out of the loop
            }
        }
    }

}

Operation results

V. summary

Briefly introduce the logical structure in Java. In fact, the logical structure in Java is similar to that in C language. I write a detailed logical structure in C language in the C language stage. Interested friends can click the link at the beginning of the article.

The input and output in Java are supplemented later in the article.

Topics: Java Back-end