process control

Published 2026-07-29 08:29 Updated 2026-10-13 17:14 1547 words 8 min read ... Page views AI-reviewed An AI proof-read this post, but it still deserves a careful read. AI-rewritten Someone else wrote the original; AI helped me rewrite and polish it.

AI-reviewed An AI proof-read this post, but it still deserves a careful read.

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, such as exhaustive method and recurrence method, as well as nested loop application examples in graphic questions. Finally, the optimization method of prime number judgment and the implementation skills of integer digit extraction are mentioned.

process control

Scanner tool class

Scanner User input can be read from the console. Console input is essentially character data,Scanner The character is parsed to 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

methodrole
nextInt()Read and parse a int
nextDouble()Read and parse a double
next()Read the next white-separated string
nextLine()Reads the rest of the current line, excluding line terminators

call nextInt()、nextDouble() Immediately after calling nextLine() When, you need to be aware 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

boolean expression is true When, the result is the value 1; otherwise the result is a 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 Select an execution branch 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 if After the branch. Branches are judged from top to bottom. After a certain condition is satisfied, other branches are no longer executed.

switch statement

switch 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 support byte、short、char、int and corresponding wrapper classes, and also support enumerations and String, do not support long、float、double and boolean。

Match a case After that, if not implemented break、return Or throws an exception, and the program continues to execute subsequent branches, which is called a breakthrough. plurality of case When sharing a section of logic, you can deliberately use penetration.

loop statement

for loop

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

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. conditions were true Execution of the loop body when.

  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);
}

computing 1 to 10 and:

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

When calculating the sum of even numbers, you can directly increase the loop variable each time 2。

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 loop is executed n times, and every inner loop is executed m times, then the inner loop is executed in total n * m times.

while loop

When only the continuation conditions are clarified and the specific number of times is not clarified, it is usually used while。

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

do… while loop

do...while The loop body is executed first and then the conditions are judged, 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 end 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 End the current cycle and move on to 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

Prime numbers are greater than 1, and only 1 and the integer of two positive divisors of 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 100 to 200 Prime numbers between:

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() return 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);

Written by AI-rewritten

If you enjoyed this, leave a comment~

Loading...