# java program logic control

Posted by abisai on Sun, 03 Oct 2021 20:39:37 +0200

# 1. Sequential structure

1. 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
```

2. If the writing order of the code is adjusted, the execution order will also change

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

# 2. Branch structure

## 2.1 if statement

1. Basic grammatical form 1:

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

2. Basic grammatical form 2:

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

3. Multiple branches of basic grammatical form 3:

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

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

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

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

```int year = 2000;
if (year % 100 == 0) {
// Judgment century leap year
if (year % 400 == 0) {
System.out.println("It's a leap year");
} else {
System.out.println("Not a leap year");
}
} else {
// Ordinary leap year
if (year % 4 == 0) {
System.out.println("It's a leap year");
} else {
System.out.println("Not a leap year");
}
}
```

7. Precautions:
(1) Overhang else problem:

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

if / else statements can be written without braces. However, statements can also be written (only one statement can be written). At this time, else matches the closest if. However, in actual development, we do not recommend this, and it is best to add braces
(2) Code style issues:

```// 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
(3) Semicolon question:

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

1. 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;]
}
}
```

2. Code example: output the 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 value of the switch, the corresponding case statement will be executed. The case statement will end when a break is encountered. If the value in the switch does not match the case, the statement in default will be executed. We suggest that a switch statement should preferably carry default
3. Precautions:
(1) Do not omit break, otherwise you will lose the effect of "multi branch selection"

```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
(2) The value in switch can only be an 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
switch(num) {
^ 1 Errors
```

(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")
```

(4)switch supports nesting, but 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;
}
```

To sum up, we find that the use of switch has great limitations

# 3. Circulation structure

## 3.1 while loop

1. Basic syntax format:

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

If the loop condition is true, the loop statement is executed; otherwise, the loop is ended
2. Code:
(1) Print numbers 1 - 10

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

(2) Calculate the sum of 1 - 100

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

(3) Calculate the factorial of 5

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

(4) Calculate 1! + 2! + 3! + 4! + 5!

```int num = 1;
int sum = 0;
// The outer loop is responsible for finding the sum of factorials
while (num <= 5) {
int factorResult = 1;
int tmp = 1;
// The inner loop is responsible for the details of factoring
while (tmp <= num) {
factorResult *= tmp;
tmp++;
}
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
3. Precautions:
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, for example:

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

1. The function of break is to end the cycle in advance
2. Code: 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++;
}
// results of enforcement
A multiple of 3 was found, by:102
```

## 3.3 continue

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

```int num = 100;
while (num <= 200) {
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++;
}
```

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

## 3.4 for loop

1. Basic grammar:

```for(Expression 1;Expression 2;Expression 3){
Circulatory body;
}
```

(1) Expression 1: used to initialize a loop variable
(2) Expression 2: loop condition
(3) Expression 3: update loop variable
Compared with the while loop, the for loop combines these three parts together and is not easy to miss when writing code
2. Example code:
(1) Print numbers 1 - 10:

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

(2) Calculate the sum of 1 - 100:

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

(3) Calculate the factorial of 5:

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

(4) Calculate 1! + 2! + 3! + 4! + 5!

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

3. Precautions:
(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

1. Basic grammar:

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

Execute the loop statement first, and then determine the loop condition
2. Code example:

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

3. Precautions:
(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

1. 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
```

(1)println output content comes with \ n, print does not \ n
(2) The format output mode of printf is basically the same as that of C language
2. Code example:

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

3. Format string

Conversion charactertype
dDecimal integer
oOctal integer
fFixed point floating point number
eExponential floating point number
gUniversal floating point number
scharacter string
ccharacter
bBoolean value
hHash code
%Percent sign

## 4.2 input from keyboard

A character can be read directly using System.in.read, but it needs to be combined with exception handling

```System.out.print("Enter a Char:");
// Compilation error
Test.java:4: error: Unreported exception error IOException; It must be captured or declared in order to be thrown
^
1 Errors
```

Correct writing:

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

This method is troublesome and we don't recommend it
2. 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
```

3. Use 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, it will prompt "low". 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"

```import java.util.Random;
import java.util.Scanner;;
class Test {
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();
}
}
```

Topics: Java Algorithm