process control

Published 2026-07-29 08:29 Updated 2026-07-29 08:29 1556 words 8 min read ... Page views

The article introduces the use of Scanner utility classes in Java, including how to read user input, common problems when processing input (such as residual line terminators), and the syntax and application scenarios of basic conditional expressions, if-else, and switch statements. At the same time, it explains in detail the use scenarios, execution processes and control keywords (break, continue) of for, while, and do-while loops, and provides analytical ideas for loop problems (exhaustive method, recurrence method), as well as practical application examples such as graphic questions and prime number judgment. Finally, it explains how to judge whether an integer is a complete square number through the Math tool class.

process control

Scanner tool class

The Scanner can read user input from the console. Console input is essentially character data, and Scanner will parse the characters into the specified type based on the method called.

basic use

Scanner scanner = new Scanner(System.in);

int number1 = scanner.nextInt();
System.out.println(number1 + 1);

int number2 = scanner.nextInt();
System.out.println(number2 + 1);

When reading input, the program waits for user input and confirms it.

common methods

MethodAction
nextInt()Read and parse a int
nextDouble()Read and parse a double
next()reads the next white-separated string
nextLine()Read the rest of the current line, excluding the line terminator

When calling nextInt() and nextDouble() immediately after calling nextLine(), you need to note that the previous method may leave a line terminator.

Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();

When reading a single character, you can read the string first and then get the first character.

String text = scanner.next();
char value = text.charAt(0);

conditional expression

Conditional expressions are also called ternary expressions, and the syntax is as follows:

布尔表达式 ? 值1 : 值2

When the Boolean expression is true, the result is the value 1; otherwise, the result is the value 2.

int a = 10;
int b = 20;
int max = a > b ? a : b;
System.out.println(max);

Conditional expressions are suitable for simple alternative assignments and are not suitable for containing a large amount of business logic.

conditional statements

if statement

if selects execution branches based on the result of the Boolean expression.

Scanner scanner = new Scanner(System.in);
System.out.println("请输入星期(1~7):");
int week = scanner.nextInt();

if (week == 1) {
    System.out.println("升旗仪式");
} else if (week == 2) {
    System.out.println("下午放假");
} else if (week == 3 || week == 5) {
    System.out.println("上体育课");
} else if (week == 4) {
    System.out.println("上科学课");
} else {
    System.out.println("放假");
}

else if and else must follow the if branch. Branches are judged from top to bottom. After a certain condition is satisfied, other branches are no longer executed.

switch statement

switch is suitable for matching multiple discrete branches based on one value.

Scanner scanner = new Scanner(System.in);
System.out.println("请输入星期(1~7):");
int week = scanner.nextInt();

switch (week) {
    case 1:
        System.out.println("升旗仪式");
        break;
    case 2:
        System.out.println("下午放假");
        break;
    case 3:
    case 5:
        System.out.println("上体育课");
        break;
    case 4:
        System.out.println("上科学课");
        break;
    default:
        System.out.println("放假");
}

Traditional switch supports byte, short, char, int and corresponding packaging classes. It also supports enumeration and String, and does not support long, float, double and boolean.

After matching a certain case, if break, return is not executed or an exception is thrown, the program will continue to execute subsequent branches, which is called penetration. When multiple case share a logic section, penetration can be deliberately used.

loop statement

for loop

When the number of cycles is clear, for cycles are usually used.

for (int i = 1; i <= 5; i++) {
    System.out.println("Hello World");
}

The execution sequence is as follows:

  1. The initialization expression is executed once.

  2. Determine cycle conditions.

  3. When the condition is true, the loop body is executed.

  4. Executes the update expression, and then returns to conditional judgment.

Common examples:

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

for (int i = 5; i >= 1; i--) {
    System.out.println(i);
}

for (char value = 'a'; value <= 'z'; value++) {
    System.out.println(value);
}

Calculate the sum of 1 to 10:

int sum = 0;
for (int i = 1; i <= 10; i++) {
    sum += i;
}
System.out.println(sum);

When calculating the even sum, you can directly increase the loop variable by 2 each time.

int sum = 0;
for (int i = 2; i <= 10; i += 2) {
    sum += i;
}

Empty conditions can form an infinite loop.

for (;;) {
    System.out.println("hello");
}

The actual code should be designed with clear exit conditions.

nested loop

Including loops again in the loop body is called nested loops.

for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= 4; j++) {
        System.out.println(i + "," + j);
    }
}

If the outer cycle is executed n times, and each inner cycle is executed m times, the inner cycle is executed n * m times in total.

while loop

When only the continuation conditions are clarified but the specific number of times is not clarified, while is usually used.

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}

do… while loop

do...while first executes the loop body and then judges the conditions, so the loop body is executed at least once.

int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5);

It is suitable for scenarios where “execute it once before deciding whether to continue”, such as menu interaction or recreating random locations that do not meet the conditions.

loop control keyword

break

break immediately ends the current cycle.

for (int i = 1; i <= 5; i++) {
    if (i == 2) {
        break;
    }
    System.out.println(i);
}

Labels can specify the end of the outer cycle, but should be used with caution to avoid incomprehensible processes.

outer:
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= 5; j++) {
        if (j == 2) {
            break outer;
        }
        System.out.println(i + "," + j);
    }
}

continue

continue ends the current cycle and enters the next cycle. It can also cooperate with the label to jump to the next round of a specified cycle.

for (int i = 1; i <= 5; i++) {
    if (i == 2) {
        continue;
    }
    System.out.println(i);
}

Analytical ideas for circulation problems

exhaustive method

List all possible values and filter results that meet the requirements based on the criteria. Suitable for questions with limited search scope.

recursive method

Starting from the known states, subsequent states are gradually calculated according to fixed relationships, including forward and backward calculations.

graphic questions

Graphic questions usually use nested loops. The outer loop controls the number of rows, and the inner loop controls the output per row.

right triangle

for (int row = 1; row <= 5; row++) {
    for (int column = 1; column <= row; column++) {
        System.out.print("*");
    }
    System.out.println();
}

diamond

Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();

for (int row = 1; row <= size; row++) {
    for (int space = 0; space < size - row; space++) {
        System.out.print(" ");
    }
    for (int star = 1; star <= 2 * row - 1; star++) {
        System.out.print("*");
    }
    System.out.println();
}

for (int row = size - 1; row >= 1; row--) {
    for (int space = 0; space < size - row; space++) {
        System.out.print(" ");
    }
    for (int star = 1; star <= 2 * row - 1; star++) {
        System.out.print("*");
    }
    System.out.println();
}

prime number judgment

A prime number is an integer greater than 1 and has only two positive factors of 1 and itself.

Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
boolean prime = number >= 2;

for (int divisor = 2; divisor <= number / divisor; divisor++) {
    if (number % divisor == 0) {
        prime = false;
        break;
    }
}

System.out.println(prime ? "是质数" : "不是质数");

It is enough to judge the square root, because if a composite number has a factor greater than the square root, there must also be a corresponding factor less than the square root.

Output the prime numbers between 100 and 200:

for (int number = 100; number <= 200; number++) {
    boolean prime = true;

    for (int divisor = 2; divisor <= number / divisor; divisor++) {
        if (number % divisor == 0) {
            prime = false;
            break;
        }
    }

    if (prime) {
        System.out.println(number);
    }
}

Get each digit of the integer

The following code outputs the digits of a non-negative integer, starting with bits.

Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();

if (number == 0) {
    System.out.println(0);
} else {
    number = Math.abs(number);
    while (number != 0) {
        System.out.println(number % 10);
        number /= 10;
    }
}

Math tool class

int value = -10;
System.out.println(Math.abs(value));

System.out.println(Math.sqrt(16));
System.out.println(Math.pow(3, 5));

System.out.println(Math.round(3.5));
System.out.println(Math.round(-3.5));

Math.sqrt() returns to double. When judging whether an integer is a complete square number, you can first take the integer square root, and then check whether the product is equal to the original number to avoid directly relying on floating point residue.

int number = 16;
int root = (int) Math.sqrt(number);
boolean perfectSquare = root * root == number;
System.out.println(perfectSquare);

If you enjoyed this, leave a comment~

... Page views
© 2026 跨越星轨的客 @Hoshiumi
Powered by theme astro-koharu · Inspired by Shoka