Program Flow Control: The flow control of a program determines how the program executes. There are three main types of flow control statements: sequential control, branch control, and loop control.

I. Sequential Control

Execution proceeds line by line from top to bottom without judgment or jumps (define first, then reference).

II. Branch Control

Allows the program to execute selectively (single branch, double branch, multi-branch).

Single Branch:

if (condition expression) {
    // Code block to execute
}
package org.example;

import java.util.Scanner;

public class condition {
    public static void main(String[] args) {
        // If over 18 years old, output "responsible for own actions"
        // First input age, then input content and judge
        Scanner myscanner = new Scanner(System.in);
        // System.in is the standard input stream (keyboard input)
        System.out.println("Please enter age:");
        int age = myscanner.nextInt();
        // nextInt() reads an integer
        /*Common reading methods:
        nextLine(): Reads an entire line of text until a newline character.
        next(): Reads the next string separated by delimiters (default is space).
        nextInt(): Reads an integer.
        nextDouble(): Reads a double-precision floating-point number.*/
        if (age >= 18) {
            System.out.println("Responsible for own actions");
        }
    }
}

Double Branch:

if (condition expression) {
    // Code block 1
} else {
    // Code block 2
}
if (age >= 18) {
    System.out.println("Responsible for own actions");
} else {
    System.out.println("Program continues");
}

Multi-branch:

if (condition expression 1) {
    // Execute code block 1
} else if (condition expression 2) {
    // Execute code block 2
} else {
    // Execute code block n
}

Multi-branch can omit the else clause. If none of the condition expressions are true, there may be no execution entry.

The else clause executes by default.

Scanner sc2 = new Scanner(System.in);
System.out.println("Please enter credit score:");
int num1 = sc2.nextInt();
if (num1 == 100) {
    System.out.println("Excellent credit");
} else if (num1 <= 99 && num1 > 80) {
    /*In Java, 99 >= num1 >= 80 is parsed as:
    First calculate 99 >= num1, resulting in a boolean type (true or false).
    Then compare this boolean result with 80, e.g., true >= 80 or false >= 80,
    but Java does not allow direct comparison between boolean and int, which will throw an error that int cannot be converted to boolean.*/
    System.out.println("Good credit");
} else if (num1 <= 80 && num1 >= 60) {
    System.out.println("Average credit");
} else {
    System.out.println("Average credit");
}

Nested Branches (Nesting beyond three levels reduces readability):

Scanner sc = new Scanner(System.in);
System.out.println("Please enter preliminary competition score:");
double grade1 = sc.nextDouble();
System.out.println("Please enter gender:");
char sex = sc.next().charAt(0);
/*First receive a string, then extract a character
The return type of sc.next() is String.
The sex variable is of type char.
Java does not allow direct assignment of String to char;
you must extract a single character from the string using methods like charAt(0).*/
if (grade1 > 8.0) {
    System.out.println("Enter final competition");
    if (sex == 'm') {
        System.out.println("Male group");
    } else {
        System.out.println("Female group");
    }
} else {
    System.out.println("Eliminated");
}

Switch Branch Structure: Without break, execution continues (executes without judgment) and does not exit.

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a character:");
char ch = sc.next().charAt(0);
switch (ch) {
    case 'a':
        System.out.println("Monday");
        break;
    case 'b':
        System.out.println("Tuesday");
        break;
    case 'c':
        System.out.println("Wednesday");
        break;
    case 'd':
        System.out.println("Thursday");
        break;
    case 'e':
        System.out.println("Friday");
        break;
    case 'f':
        System.out.println("Saturday");
        break;
    case 'g':
        System.out.println("Sunday");
        break;
    default:
        System.out.println("Invalid input");
        break;
}

(1) The data type of the expression should match the constant type after case.

(2) The return value of switch (expression) must be one of (byte, short, int, char, enum [enumeration], String).

(3) Values in case clauses can only be constants, not variables.

(4) The default clause is optional (can be omitted). Without default and no matching constants, there is no output.

(5) Break is used to exit the switch statement; without it, execution proceeds sequentially until exiting the switch.

Scanner sc = new Scanner(System.in);
System.out.println("Please enter score:");
double grade = sc.nextDouble();
if (grade >= 0 && grade <= 100) {
    // To make switch judge double type, cast to int
    switch ((int) (grade / 60)) {
        // Score/60; judge 1/0 (cast to int, programming idea)
        case 0:
            System.out.println("Fail");
            break;
        case 1:
            System.out.println("Pass");
            break;
        default:
            System.out.println("Excellent");
            break;
    }
} else {
    System.out.println("Invalid input");
}

(6) Use switch when judging a small number of specific values that match byte, short, int, char, enum (enumeration), or String.

(7) Use if for range judgments where the result is a boolean type.

III. Loop Control

For Loop Control

int i;
for (i = 0; i < 10; i++) {
    System.out.println("Lao Han talks about Java");
}

(1) Four loop elements:

1. Loop variable initialization

2. Loop condition

3. Loop operation: can have multiple statements

4. Loop variable iteration

While Loop

int j = 40;
while (j <= 200) {
    if (j % 2 == 0) {
        System.out.println("j = " + j);
    }
    j++;
}

Simplify complex problems, start with fixed values then generalize (facilitates thinking).

Do-While Loop (executes first, then judges)

int i = 1;
do {
    System.out.println("Hanshunping Education" + i);
    i++;
} while (i <= 10);  // Semicolon at the end for boolean expression
Scanner sc = new Scanner(System.in);
System.out.println("Will you repay the money?");
do {
    String a = sc.next();
    if (a.equals("Not repaying")) {
        System.out.println("Start fighting");
    } else {
        System.out.println("ok");
        break;
    }
} while (0 < 1);

Nested Loops (recommended up to three levels): For business optimization, treat the inner loop as the loop body of the outer loop, executing m*n times.

package org.example;

import java.util.Scanner;

public class cycle05 {
    public static void main(String[] args) {
        // Calculate score statistics for 3 classes, each with 5 students,
        // find the average score of each class and the average score of all classes [student scores input from keyboard]
        // Count the number of passing students in 3 classes, 5 students per class
        // Idea analysis:
        /*Simplify complex problems
     * (1) First calculate scores for one class with 5 students using for loop
     *   1.1 Create a scanner object to receive user input (decimal numbers)
     *   1.2 Calculate the class average, define a double sum to accumulate the 5 students' scores
     * (2) Calculate average scores for 3 classes (each with 5 students)
     * (3) Average score of all classes
     *     3.1 Define a variable, double total, to accumulate all students' scores
     *     3.2 After multi-loop ends, total/(3*5)
     * (4) Count passing students in three classes
     *     4.1 Define variable int pass = 0; increment pass by 1 for each passing score
     * (5) Optimize for efficiency, readability, and structure*/
        Scanner sc = new Scanner(System.in);
        double total = 0;
        int pass = 0;
        for (int i = 1; i <= 3; i++) {
            double sum = 0;
            for (int j = 1; j <= 5; j++) {
                System.out.println("Please enter score of student " + j + " in class " + i);
                double score = sc.nextDouble();
                if (score >= 60) {
                    pass++;
                }
                System.out.println("Score of student " + j + " in class " + i + " is: " + score);
                sum += score;
            }
            System.out.println("sum = " + sum + " average score = " + sum / 5);
            total += sum;
        }
        System.out.println("total = " + total + " overall average score = " + total / (3 * 5));
        System.out.println("pass = " + pass);
    }
}
package org.example;

public class cycle06 {
    public static void main(String[] args) {
        // 9x9 multiplication table
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "*" + i + "=" + (i * j) + "\t");
                // \t is a tab character for alignment
            }
            System.out.println();
            // \n is a newline character
        }
    }
}
package org.example;

public class stars {
    public static void main(String[] args) {
        // Print hollow pyramid
        /*Idea analysis
     * Simplify complex problems
     * 1. First print a 5x5 rectangle
     * 2. Print half a pyramid
     * 3. Print a pyramid
     * 3.1 Find pattern: 2*layers - 1
     * 3.2 Total layers equal current number of spaces
     * 4. Print hollow pyramid
     * 5. Start with fixed values then generalize: int total == 5*/
        int total = 10;
        for (int i = 1; i <= total; i++) {
            // Print spaces before printing *
            for (int k = 1; k <= total - i; k++) {
                System.out.print(" ");
            }
            for (int j = 1; j <= 2 * i - 1; j++) {
                // Print * at the first and last positions
                // Print all * for the last layer
                if (j == 1 || j == 2 * i - 1 || i == total) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}

Break Jump Control Statement

The break statement can specify which layer to exit.

label1 is a label, defined by the programmer.

Specifying a label after break exits at that label.

In actual development, it is recommended to avoid using labels (reduces readability).

Without specifying a label, break exits the nearest loop body by default.

abc1:
for (int j = 0; j < 4; j++) {
    abc2:
    for (int i = 0; i < 10; i++) {
        if (i == 2) {
            break abc1;
        }
        System.out.println(i);
    }
}
package org.example;

import java.util.Scanner;

public class Btest02 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        for (int i = 1; i <= 3; i++) {
            System.out.println("Please enter username:");
            String username = sc.next();
            System.out.println("Please enter password:");
            String password = sc.next();
            if (username.equals("DingZhen") && password.equals("123456")) {
                System.out.println("Login successful");
                break;
            } else {
                System.out.println("Incorrect username or password");
                System.out.println((3 - i) + " attempts remaining");
                if (i == 3) {
                    System.out.println("Login failed");
                }
            }
        }
    }
}

Continue is used to end the current loop and continue with the next iteration.

When the continue statement appears in a nested loop, it can specify which loop to skip using a label, following the same rules as labels with break.

Return exits the current method.

Exercises

package org.example;

public class Wtest06 {
    public static void main(String[] args) {
        /*
        1. Print numbers from 1-100 that are not divisible by 5
        2. Print 5 numbers per line, use a counter to count the number of outputs*/
        int i = 0;
        for (int j = 1; j <= 100; j++) {
            if (j % 5 != 0) {
                System.out.print(j + "\t");
                i++;// Count the number of outputs
            }
            if (i == 5) {
                System.out.println();
                i = 0;
            }
        }
    }
}
package org.example;

import java.util.Scanner;

public class Wtest07 {
    public static void main(String[] args) {
        // Output lowercase a-z and uppercase letters A-Z
        /*Idea analysis: ASCII code + for loop
        * 1. b = a + 1
        * c = a + 2
        * Characters can be compared and used as integers*/
        for (char c1 = 'a'; c1 <= 'z'; c1++) {
            System.out.print(c1 + "\t");
        }
        System.out.println();
        for (char c2 = 'Z'; c2 >= 'A'; c2--) {
            System.out.print(c2 + "\t");
        }
    }
}
package org.example;

public class Wtest08 {
    public static void main(String[] args) {
        /*1 - 1/2 + 1/3 - 1/4 + … - 1/100
        * 1. There are 100 numbers, numerator is fixed as 1, denominator ranges from 1-100
        * Positive sign for odd denominators, negative sign for even denominators
        * A hidden trap here: use 1.0 as the numerator to maintain precision*/
        double a = 1;
        double b = 1;
        double sum = 0;
        for (; a <= 100; a++) {
            if (a % 2 == 0) {
                sum = sum - b / a;
            } else if (a % 2 != 0) {
                sum = sum + b / a;
            }
        }
        System.out.println(sum);
    }
}
package org.example;

public class Wtest09 {
    public static void main(String[] args) {
        /*Calculate 1 + (1+2) + (1+2+3) + … + (1+2+3+…+100)
        * There are 100 terms to sum, each term increases gradually,
        * which is like a double loop*/
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            // i can represent the term number and also the last number in the current term
            for (int j = 1; j <= i; j++) {
                // Inner loop sums from 1 to i
                sum = sum + j;
            }
        }
        System.out.print(sum + "\t");
    }
}

Avatar

By BytePilot

Because sharing makes us better. Let’s learn, build, and grow — one byte at a time.

Leave a Reply

Your email address will not be published. Required fields are marked *