Java program flow control

1. Process control statement

Java provides some process control statements to control the execution process of the program
Sequential structure - program default process
Branch structure - if, switch
Loop structure - for, white, do... while

1. Branch structure

1.if branch

The code that executes a branch is determined according to the determined structure (true or false)
The if branch has three formats

Format 1
if(Conditional expression) {
	Sentence body;
}

Format 2
if(Conditional expression) {
    Statement body 1
} else {
    Statement body 2
}

Format 3
if(Conditional expression 1) {
    Statement body 1
} else if(Conditional expression 2){
    Statement body 2
} else if(Conditional expression 3) {
    Statement body 3
} 
...
else {
    Statement body n
}
// Requirements: if the score is higher than 60, you will pass, otherwise you will fail
int score = 70;
if(score>=60 && score<=100) {
    System.out.println("Qualified results");
}
// Demand: if you are older than 18, you will be an adult, otherwise you will be a minor
int age = 20;
if(age >=18) {
    System.out.println("You are an adult");
} else {
    System.out.println("You are under age");
}
// Requirements: above 80 A, above 70 B, above 60 C, below 60 D
int score2 = 40;
if (score2 > 0 && score2 < 60) {
    System.out.println("D");
} else if (score2 >= 60 && score2 < 70) {
    System.out.println("C");
} else if (score2 >= 70 && score2 < 80) {
    System.out.println("B");
} else if (score2 >= 80 && score2 <= 100) {
    System.out.println("C");
} else {
    System.out.println("The score entered is incorrect");
}
2.switch branch

It is also a branch to be executed by matching conditions. It is suitable for branch selection of value matching. It has clear structure and good format

Execution process:

1. First execute the value of the expression and take this value to match the value after case

2. Execute the matching case whose value is true, and jump out of the switch branch in case of a break

3. If the values after case do not match, execute the default code

swith(expression) {
    case Value 1:
        Execute code...;
    	break;
    case Value 2: 
    	Execute code...;
    	break;
    ...
    case value n-1: 
    	Execute code
}
String today = "Wednesday";
switch (today){
    case "Monday":
        System.out.println("Fishing at work");
        break;
    case "Tuesday":
        System.out.println("Keep fishing");
        break;
    case "Wednesday":
        System.out.println("leave");
        break;
    case "Thursday":
        System.out.println("Wait for the weekend");
        break;
    case "Friday":
        System.out.println("Not to go to work tomorrow");
        break;
    default:
        System.out.println("vacation");
}

be careful:

1. Expression types can only be byte, short, int and char. JDK5 starts to support enumeration, and JDK7 starts to support String, but does not support double, float and long

2. The value given by case cannot be repeated, and can only be literal, not variable

3. Each branch must end with break, otherwise case penetration will occur

int a = 3;
switch (a) {
    case 3 :
        System.out.println("a=3");
    case 4:
        System.out.println("a=4"); // a = 3   a = 4
        break;
    default:
        return;
}

Penetration of swich

If the code is executed to a case block that does not write a break, it will directly enter the next case block to execute the code (without any matching) and will not jump out of the branch until the break. This is the penetration of swich

int month = 7;
switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
        System.out.println(month+"The month is 31 days");
        break;
    case 2:
        System.out.println(month+"There are 28 days in a normal year and 31 days in a leap year");
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        System.out.println(month+"The month is 30 days");
        break;
    default:
        System.out.println("Please enter the correct month");
}

2. Circulation structure

1.for loop

Control the repeated execution of a piece of code many times

Format:

for(Initialization statement;Cycle condition;Iterative statement) {
    Loop body statement(Repeatedly executed code)
}

power

// Output HelloWorld 3 times
for(int i = 0; i < 3; i++) {
    System.out.println("hello");
}
2.while loop

Format:

Initialization statement:
 while(Cycle condition) {
     Loop body statement(Repeatedly executed code);
     Iterative statement;
 }
int i =0;
while(i<3) {
    System.out.println("Hello World");
    i++;
}

Note: if it is not clear how many times to cycle, you can choose to implement it with while

Both while and for can be implemented

3.do... while loop

Execute first and then judge the cycle condition

Initialization statement;
do {
    Loop body statement;
    Iterative statement;
}while(Cycle condition)

Characteristics of do while loop: the loop body must be executed once first

int i = 0;
do{
    System.out.println("hello World");
    i++;
} while(i<3);
4. Differences

for loop and while loop (judgment before execution)

do... While (execute first and then judge)

The difference between for and while

The execution process of for loop and while loop is the same

If the number of cycles is known, it is recommended to use the for loop. If it is not clear how many cycles to cycle, it is recommended to use the while loop

In the for loop, the variables that control the loop can only be used in the loop. In a While loop, the variables that control the loop can continue to be used after the loop

5. Dead cycle

It will be executed circularly and will not stop without intervention

for(;;) {
    System.out.println("hello");
}
// Classic writing
while(true) {
     System.out.println("hello");
}
do {
     System.out.println("hello");
} while(true)
6. Nested loop

Loop contains loop

for (int i = 0;i<5;i++) {
    for(int j=0;j<3;j++) {
        System.out.println(j+"j");
    }
    System.out.println(i+"i");
}
7. Jump keyword

break: jump out and end the execution of the current loop

continue: used to jump out of the current execution of the current cycle and enter the next cycle

be careful:

break:Can only be used to end the loop or end the loop switch Branch execution
continue: It can only be used in a loop
7.Random number

Function: used to obtain random numbers in the program

1. Guide Package

import java.util.Random;

2. Write a line of code to represent the obtained random number object

Random r = new Random();

3. Call the function of random number to obtain the random number of 0-9

int number = r.nextInt(10)

be careful:

nextInt(n) function can only generate random numbers between 0 and n-1, excluding n

Random r = new Random();
// Call the nextInt method to return an integer random number
int data = r.nextInt(10);
System.out.println(data);

Random random number how to generate random numbers between 65-91

65-91=>(0-26)+65
int number = r.nextInt(27)+65

2. Cases

1. Summation

Requirements: sum the data between 1-5 and output the summation results on the console

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

2. Odd sum

Requirements: find the odd sum between 1-10, and output the sum result on the console

int sum = 0;
for(int i =1; i <= 10; i++) {
    if(i % 2 == 1) {
        sum += i;
    }
}
System.out.println(sum); // 25

Method 2

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

3. Number of daffodils

Requirement: output all "daffodils" on the console

1. Narcissus is a three digit number

2. The cubes of the digits, tens and hundreds of daffodils are equal to the original number

int count = 0;
// Narcissistic number 
for(int i = 100; i <= 999; i++) {
    // Bit
    int ge = i % 10;
    // Ten
    int shi = i / 10 % 10;
    // Hundredth
    int bai = i / 100;
    if(ge*ge*ge + shi*shi*shi + bai*bai*bai == i) {
        count++;
        System.out.print(i+"\t");
    }
}
System.out.println("\n What is the number of daffodils"+count);

4. Mount Everest

Everest can be folded into 480.88mm (the height of Everest in the world), if it is the largest peak in the world, how much does it need to be folded into 480.88mm

analysis:

1. Define variables to store the height of Mount Everest and the height of paper

2. Use the while cycle. The cycle condition is (paper thickness < peak height). The paper folding is controlled internally. Each time the paper is folded, the paper thickness is twice the original. The counting variable is defined outside the cycle, and the variable is increased by 1 for each folding

 // Mount Qomolangma
// Defines the height of the peak and the thickness of the paper
double peakHeight = 8848860;
double paperThickness = 0.1;
int count = 0;
// Define a while loop to control paper folding
while (paperThickness < peakHeight) {
    paperThickness *= 2;
    count++;
}
System.out.println("Number of folds"+count);
System.out.println("Final thickness of paper"+paperThickness);

5. Password verification

Requirements: the system password is 123456. Please input the password continuously for verification. If the verification is wrong, output the wrong password. The verification is successful. Welcome to the system and stop the program

 // 1. Define the correct password
int okPwd = 123456;
// 2. Define an endless loop and continuously enter password authentication
Scanner sc = new Scanner(System.in);
while(true) {
    System.out.println("Please enter the correct password:");
    int pwd = sc.nextInt();
    // Determine whether the password is correct
    if(pwd == okPwd) {
        System.out.println("Login successful");
        break;
    } else {
        System.out.println("Password error");
    }
}

6. Loop nesting

Requirement: use * on the console to print out 4 rows and 5 columns of rectangles

for(int i=0;i<4;i++) {
    for (int j =0;j<5;j++) {
        System.out.print("*");
    }
    System.out.println();
}

7. Case: number guessing game

Demand: randomly generate a data between 1-100, prompt the user to guess, guess the big prompt is too big, guess the small prompt is too small, and know that the guess is right to end the game

 // Any number between 1 and 100
Random r = new Random();
int luckNumber = r.nextInt(100)+1;
Scanner sr = new Scanner(System.in);
while (true) {
    System.out.println("Please enter data(1-100)");
    int guessNumber = sr.nextInt();
	// Guess correctly
    if(guessNumber>luckNumber){
        System.out.println("The guessed data is too large");
    }else if(guessNumber<luckNumber) {
        System.out.println("The guessed data is too small");
    }else {
        System.out.println("Congratulations on your guess");
        break;
    }
}

Keywords: Java Back-end JavaSE

Added by PHPHorizons on Mon, 14 Feb 2022 09:14:14 +0200