# 1. Sequential structure

The sequential structure is relatively simple. For example, the code we wrote before is a sequential structure, which is executed line by line in the order of code writing

```System.out.println("aaa");
System.out.println("bbb");
System.out.println("ccc");
// Operation results
aaa
bbb
ccc
```

If you adjust the writing order of the code, the execution order also changes

```System.out.println("aaa");
System.out.println("ccc");
System.out.println("bbb");
// Operation results
aaa
ccc
bbb
```

# 2. Branch structure

## 2.1 if statement

Basic grammatical form 1

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

Basic grammatical form 2

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

Basic grammatical form 3 multi branch case

```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
}
```

Code example 1: determine whether a number is odd or even

```int num = 10;
if (num % 2 == 0) {
System.out.println("num It's an even number");
} else {
System.out.println("num It's an odd number");
}
//When adding input (generally not recommended)
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();//The input string plus the Line parameter can have spaces
System.out.println(str);
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.println("num It's an even number");
} else {
System.out.println("num It's an odd number");
}
```

Code example 2: determine whether a number is positive or negative

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

Code example 3: determine whether a year is a leap year

```        int year = 2000;
if( year % 100 == 0) {
//Century leap year
if(year % 400 == 0) {
System.out.println(year + "It's a leap year");
} else {
System.out.println(year + "Not a leap year");
}
}else {
//Ordinary leap year
if( year % 4 == 0) {
System.out.println(year + "It's a leap year");
}else {
System.out.println(year + "Not a leap year");
}
//Optimize
int year = 2000;
if( (year % 100 != 0 && year % 4 == 0) || year % 400 == 0) {
System.out.println(year + "It's a leap year");
} else {
System.out.println(year + "Not a leap year");
}
//scanner.close() can be added at the end;

//You can also set int year = 2000; Replace with the following code
Scanner scanner = new Scanner(System.in);
int year = scanner.nextInt();
```

Note 1 suspension else problem

```        int x = 10;
int y = 10;
if (x == 10)
if (y == 10)
System.out.println("aaa");
else
System.out.println("bbb");
int x = 10;
int y = 10;
if (x == 10) {
if (y == 10) {
System.out.println("aaa");
} else {
System.out.println("bbb");
}
} //aaa
```

if / else statements can be written without parentheses. However, statements can also be written (only one statement can be written). At this time, else matches the closest if
But we don't recommend it in actual development. It's best to add braces

Note 2 code style

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

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

Although both methods are legal, style 1 is more recommended in Java, {on the same line as if / else

Note 3 semicolon problem

```int x = 20;
if (x == 10); {
System.out.println("hehe");
}
// Operation results
hehe
```

An extra semicolon is written here, 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

## 2.2 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;]
}
}
```

Code example: output week according to the value of day

```        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("Incorrect input");
break;
}
```

Depending on the switch value, the corresponding case statement will be executed. The case statement will be ended when a break is encountered
If the value in switch does not have a matching case, the statement in default will be executed
We suggest that a switch statement should preferably carry default

Note 1 do not omit break, otherwise the effect of "multi branch selection" will be lost

```        int day = 1;
switch(day){
case 1:
System.out.println("Monday");
//break;
case 2:
System.out.println("Tuesday");
break;
}
// Operation results
Monday
Tuesday
```

We find that when we don't write break, the case statements will be executed downward in turn, thus losing the effect of multiple branches

Note 2 the value in switch can only be integer | enumeration | character | string

```double num = 1.0;
switch(num) {
case 1.0:
System.out.println("hehe");
break;
case 2.0:
System.out.println("haha");
break;
}
// Compilation error
Test.java:4: error: Incompatible types:from double Convert to int There may be losses
```

1. Interview question: what are the data types that cannot be used as Switch parameters in java?
Long float double boolean
2.JDK1.5 starts to introduce enumeration: enumeration can also be used as a switch parameter

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~

```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;
}
//hehe
```

The beauty of the code is also an important standard. After all, this is the face world. (dog head)
To sum up, we find that the use of switch has great limitations

# 3. Circulation structure

## 3.1 while loop

Basic syntax format:

```while(Cycle condition){
Circular statement;
}
```

If the loop condition is true, the loop statement is executed; otherwise, the loop is ended
Code example 1: print numbers 1 - 10

```int num = 1;
while(num <= 10) {
System.out.println(num);
num++;
}
//Another thought
int num = 1;
int sum = 0;
while(num <= 10) {
sum = sum +num;
System.out.println(num);
num++;
}
//1 2 3 4 5 6 7 8 9 10
```

Code example 2: calculate the sum of 1 - 100

```int n = 1;
int result = 0;
while (n <= 100) {
result += n;
n++;
}
System.out.println(result);
//5050
```

Code example 3: calculate the factorial of 5

```        int n = 1;
int result =1;
while( n <= 5) {
result *= n;
n++;
}
System.out.println(result);

```

Code example 4: calculate 1! + 2! + 3! + 4! + 5!

```        int num = 1;
int sum = 0;
while(num <= 5) {
int factorResult =1;
int tmp = 1;
while( tmp <= num) {
factorResult *= tmp;
tmp++;
}
//System.out.println(factorResult);
sum += factorResult;
num++;
}
System.out.println("sum = "+sum);
```

Here we find that when there are multiple loops in a code, the complexity of the code is greatly improved, and the more complex code is more prone to errors. Later, we will adopt a simpler method to solve this problem

matters needing attention

1. Similar to if, the statement under while may not write {}, but only one statement can be supported when it is not written. It is recommended to add {}
2. Similar to if, the {suggestion after while is written on the same line as while
3. Similar to if, do not write more semicolons after while, otherwise the loop may not execute correctly
```int num = 1;
while (num <= 10); {
System.out.println(num);
num++;
}
// results of enforcement
```

At this time, it is the statement body of 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 the code

## 3.2 break

The function of break is to end the cycle ahead of time
Code example: find the multiple of the first 3 in 100 - 200

```        int num =100;
while( num < 200) {
if(num % 3 == 0) {
System.out.println("A multiple of 3 was found, by:"+num);
break;
}
num++;
}
// The execution result found a multiple of 3: 102
```

Executing break will end the loop

## 3.3 continue

The function of continue is to skip this cycle and immediately enter the next cycle
**Code example: * * find multiples of all 3 in 100 - 200

```        int num = 1;
while(num < 10) {
if(num % 3 != 0) {
num++;// Don't forget the + + here! Otherwise it will loop
continue;
}
System.out.println("A multiple of 3 was found, by:" + num);
num++;
}
```

**Code example: * * find a number between 1 and 100 that can be divided by both 3 and 5

```        //When i%15 is negative
int i = 1;
while(i<100) {
if(i % 15 != 0) {
i++;
continue;
}
System.out.println(i);
i++;
}

//When i%15 is affirmative
/*int n = 1;
while(n <= 100) {
if(n % 15 == 0) {
System.out.print(n+" ");
n++;
continue;
}
n++;
}*/
//15 30 45 60 75 90

//No, continue
//sure
/*for(int i = 1;i <= 100;i++) {
if(i % 3 == 0 && i % 5 == 0) {
System.out.println(i);
}
}*/
```

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

be careful:
Both break and continue must be in the loop, and you can only jump out of the nearest loop. You can't directly jump out of multi-layer loops
[Special: break can be in switch

Understand:
There is no goto in java. Goto is a reserved word at present, that is, it will be enabled at any time. But even if you know goto, don't use it. You may be diss by your boss!!!
reason:
1. It is difficult to debug if there is an error

## 3.4 for loop

Basic grammar

```for(Expression 1;Expression 2;Expression 3){
Circulatory body;
}
```
• Expression 1: used to initialize a loop variable
• Expression 2: loop condition expression
• Expression 3: update loop variable

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

Code execution order:
First execute expression 1, then expression 2, then the loop body, and finally expression 3.

Code example 1: print numbers 1 - 10

```        int i = 0;
for(i = 1; i <= 10; i++) {
System.out.println(i);
}
}
//Or write int directly into it
for(int i = 1; i <= 10; i++) {
System.out.println(i);
}
```

Code example 2: calculate the sum of 1 - 100

```        int i = 0;
int sum = 0;
for(i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("sum = " + sum);
// results of enforcement
5050
```

Code example 3: calculate the factorial of 5

```        int i = 0;
int result = 1;
for(i = 1;i <= 5;i++) {
result *=i;
}
System.out.println("result = " + result);
//120
```

Code example 4: calculate 1+ 2! + 3! + 4! + 5!

```        int sum = 0;
for(int j=1;j<=5;j++) {
int result = 1;
for(int i = 1;i <= j;i++) {
result *=i;
}
sum += result;
}
System.out.println("sum = " + sum);
//153

//Method II
int ret = 1;
int all = 0;
for(int a = 1;a<= 5;a++) {
ret *= a;
all += ret;
}
System.out.println(all);//153
```

Precautions (similar to while loop)

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

## 3.5 do while loop (optional)

Basic grammar

```do{
Circular statement;
}while(Cycle condition);
```

Execute the loop statement first, and then determine the loop condition
Code example: print 1 - 10

```        int n = 1;
do {
System.out.println(n);
n++;
}while(n <= 10);
```

matters needing attention

1. Don't forget the semicolon at the end of the do while loop
2. Generally, do while is rarely used, and for and while are recommended

# 4. Input and output

## 4.1 output to console

Basic grammar

```        System.out.println("msg"); // Output a string with newline
System.out.print("msg"); // Output a string without line breaks
System.out.printf("format, msg"); // Format output
```
• println output content comes with \ n, print does not \ n
• The format output mode of printf is basically the same as that of C language

Code example

```        System.out.println("hello world");
int x = 10;
System.out.printf("x = %d\n", x);
```

format string There's no need to remember this form. Just check it as needed

## 4.2 input from keyboard

A character can be read directly using System.in.read, but it needs to be combined with exception handling (which will be highlighted later)

```System.out.print("Enter a Char:");
char i = (char)
System.out.println("your char is :"+i);  // Compilation error Test.java:4: error: unreported exception error IOException; it must be caught or declared to throw char i = (char) System.in.read(); 1 error
```

Correct writing

```import java.io.IOException; // IOException package needs to be imported
try {
System.out.print("Enter a Char:");
char i = (char)
} catch (IOException e) {
System.out.println("exception");
}
```

This method is troublesome and we don't recommend it

Use Scanner to read string / integer / floating point number

```import java.util.Scanner; // The util package needs to be imported
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int age = sc.nextInt();
float salary = sc.nextFloat();
System.out.println("full name: "+name+"\n"+"Age:"+age+"\n"+"Salary:"+salary);
sc.close(); // Note that remember to call the close method

// results of enforcement
Zhang San
18
1000
full name: Zhang San
Age: 18
Salary: 1000.0
```
```        Scanner a = new Scanner(System.in);
String b = a.nextLine();
float c = a.nextFloat();
System.out.println(b);
System.out.println(c);
a.close();

```

Generally speaking, print the string first and then the number. You don't have to care when you're online oj.

Use the Scanner loop to read N numbers

```Scanner sc = new Scanner(System.in);
double sum = 0.0;
int num = 0;
while (sc.hasNextDouble()) {
double tmp = sc.nextDouble();
sum += tmp;
num++;
}
System.out.println("sum = " + sum);
System.out.println("avg = " + sum / num);
sc.close();
// results of enforcement
10
40.0
50.5
^Z
sum = 150.5
avg = 30.1
```

Note: when looping multiple data, use ctrl + z to end the input (ctrl + z on Windows and Ctrl + D on Linux / MAC)

# 5. Number guessing game

Rules of the game:
The system automatically generates a random integer (1-100), and then the user enters a guessing number. If the entered number is smaller than the random number, the prompt "low" will be prompted
If the entered number is larger than the random number, it will prompt "high". If the entered number is equal to the random number, it will prompt "guessed right"

Reference code

``` public static void main(String[] args) {
Random random = new Random(); //The default random seed is system time
Scanner sc = new Scanner(System.in);
int toGuess = random.nextInt(100);
// System.out.println("toGuess: " + toGuess);
while (true) {
System.out.println("Please enter the number you want to enter: (1-100)");
int num = sc.nextInt();
if (num < toGuess) {
System.out.println("Low");
} else if (num > toGuess) {
System.out.println("High");
} else {
System.out.println("You guessed right");
break;
}
}
sc.close();
}
}
```

Tags: Java Back-end

Posted on Sat, 04 Dec 2021 18:43:06 -0500 by hoyo