Java logic control

 


Table of contents

1. Sequential structure

2. Branch structure

1. if statement

(1) Grammar format 1Edit

(2) Grammar format 2 Edit

(3) Grammar format 3

2. switch statement

3. Loop structure

1. while loop

2、break

3、continue

4. for loop

5. do while loop

4. Input and output

1. Output to the console

2. Input from keyboard

5. Number guessing game


1. Sequential structure

The sequence structure is relatively simple, and is executed line by line in the order in which the code is written.

If you adjust the writing order of the code, the execution order will also change.

2. Branch structure

1. if statement


(1) Grammar format 1

If the result of the Boolean expression is true, the statement in if is executed, otherwise it is not executed.


(2) Grammar format 2

If the result of the Boolean expression is true, the statement in if is executed, otherwise the statement in else is executed.
 

(3) Grammar format 3

If expression 1 is true, execute statement 1. Otherwise, expression 2 is true, execute statement 2. Otherwise, execute statement 3.

[Notes]
        Code style

2. switch statement

basic grammar

Execution process:
1. Calculate the value of the expression first
. 2. Compare with the case in sequence. Once there is a match, execute the statement under the item until break is encountered.
3. When the value of the expression does not match the listed items, When, execute default

[Note]
Constant values ​​after multiple cases cannot be repeated.
The brackets of switch can only contain the following types of expressions:
        basic types: byte, char, short, int. Note that they cannot be long type
        reference types: String constant string, enumeration type

        Don't omit break, otherwise you will lose the effect of "multi-branch selection"

        switch cannot express complex conditions.
        Although switch supports nesting, it is very ugly and is generally not recommended~

3. Loop structure

1. while loop

Basic syntax format:

If the loop condition is true, the loop statement is executed; otherwise, the loop ends.
 

Code example 1: Print numbers 1 - 10

Notes
1. Similar to if, the statement below while does not need to be written with { }, but it can only support one statement if not written. It is recommended to add { }
2. Similar to if, it is recommended that the { after while be written with while. On the same line.
3. Similar to if, do not write more semicolons after while, otherwise the loop may not be executed correctly.

2、break

The function of break is to end the loop early.

Code example: Find the first multiple of 3 from 100 - 200
 

int num = 100;
while (num <= 200) {
if (num % 3 == 0) {
System.out.println("找到了 3 的倍数, 为:" + num);
break;
} n
um++;
} 
// 执行结果
//找到了 3 的倍数, 为:102

Execution to break will end the loop
 

3、continue

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


Code example: Find all multiples of 3 from 100 - 200

When the continue statement is executed, it will immediately enter the next loop (determine the loop condition), so that the print statement below will not be executed.
 

4. for loop

【Basic Grammar】

Expression 1: Used to initialize the initial value setting of the loop variable. It is executed at the beginning of the loop and only executed once.
Expression 2: Loop condition. If it is full, the loop continues, otherwise the loop ends.
Expression 3: Loop variable update method.
 

[Code Example]
        Calculate the sum of 1 - 100

[Notes] (Similar to while loop)
1. Similar to if, the following statement of for does not need to write { }, but it can only support one statement if not written. It is recommended to add { }
2. Similar to if, for The following { is recommended to be written on the same line as while.
3. Similar to if, do not write more semicolons after for, otherwise the loop may not be executed correctly.
4. Like the while loop, use continue to end a single loop and end the entire loop. Use break
 

5. do while loop

【Basic Grammar】

The loop statement is executed first, and then the loop condition is determined. If the loop condition is established, execution continues, otherwise the loop ends.

For example: print 1 - 10

[Notes]
1. Don’t forget the semicolon at the end of the do while loop.
2. Generally, do while is rarely used, and it is more recommended to use for and while.
 

4. Input and output

1. Output to the console

basic grammar

The output content of println comes with \n, and print does not contain \n.
The formatted output method of printf is basically the same as the printf of C language.

 

code example

Format string

There is no need to memorize this form, just check it when needed.
 

2. Input from keyboard

Use Scanner to read strings/integers/floating point numbers
 

import java.util.Scanner; // 需要导入 util 包
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的姓名:");
String name = sc.nextLine();
System.out.println("请输入你的年龄:");
int age = sc.nextInt();
System.out.println("请输入你的工资:");
float salary = sc.nextFloat();
System.out.println("你的信息如下:");
System.out.println("姓名: "+name+"\n"+"年龄:"+age+"\n"+"工资:"+salary);
sc.close(); // 注意, 要记得调用关闭方法
// 执行结果
请输入你的姓名:
张三
请输入你的年龄:
18
请输入你的工资:
1000
你的信息如下:
姓名: 张三
年龄:18
工资:1000.0

Use Scanner to loop through N numbers and find their average
 

Scanner sc = new Scanner(System.in);
int sum = 0;
int num = 0;
while (sc.hasNextInt()) {
int tmp = sc.nextInt();
sum += tmp;
num++;
} S
ystem.out.println("sum = " + sum);
System.out.println("avg = " + sum / num);
sc.close();
// 执行结果
10
40.0
50.5
^Z
sum = 150.5
avg = 30.1

Precautions:

When looping through multiple inputs, use ctrl + z to end the input (ctrl + z on Windows, ctrl
+ d on Linux/Mac).
 

5. Number guessing game

Game rules:
The system automatically generates a random integer (1-100), and then the user enters a guessed number. If the entered number is smaller than the random number, it will prompt "low".
If the entered number is larger than the random number, It will prompt "higher". If the entered number is equal to the random number, it will prompt "guessed correctly".

Reference Code
 

import java.util.Random;
import java.util.Scanner;;
class Test {
public static void main(String[] args) {
Random random = new Random(); // 默认随机种子是系统时间
Scanner sc = new Scanner(System.in);
int toGuess = random.nextInt(100);
// System.out.println("toGuess: " + toGuess);
while (true) {
System.out.println("请输入要输入的数字: (1-100)");
int num = sc.nextInt();
if (num < toGuess) {
System.out.println("低了");
} else if (num > toGuess) {
System.out.println("高了");
} else {
System.out.println("猜对了");
break;
}
} 
sc.close();
}
}

Thanks for watching~

Guess you like

Origin blog.csdn.net/cool_tao6/article/details/132702704