JavaSE_04 [ process control statement ]

Posted by dinno2 on Wed, 09 Mar 2022 14:11:54 +0100

JavaSE_04 [ process control statement ]

Today's content

  • for loop statement
  • while loop statement
  • do... while loop statement
  • break
  • continue

Learning objectives

  • Understand the format and execution process of for statement
  • Understand the format and execution flow of while statement
  • Understand the format and execution flow of do... while statement
  • Understand the meaning of the break and continue statements
  • Understand the execution process of dead cycle
  • Understand the execution process of loop nesting

Chapter III process control (Continued)

No matter which programming language, it will provide two basic process control structures: branch structure and loop structure. The branch structure is used to selectively execute a piece of code according to the conditions, and the loop structure is used to repeatedly execute a piece of code according to the loop conditions.

3.8 loop statement: for loop

A loop statement can repeatedly execute a piece of code when the loop conditions are met. This repeatedly executed code is called a loop body statement. When the loop body is repeatedly executed, you need to modify the loop variable to make the loop judgment condition false, so as to end the loop. Otherwise, the loop will continue to execute and form an endless loop.

1. for loop statement format:

for(Initialization statement①; Circular conditional statement②; Iterative statement④){
	Loop body statement③
}
for(;;){
    Circular aspect sentence block;//If there is no statement jumping out of the loop body in the loop body, it is an dead loop
}

be careful:

(1)for(;;) Two of the; It can't be more or less

(2) Loop condition must be of type boolean

(3) If the circular condition statement ② is omitted, it defaults to the circular condition

Execution process:

  • Step 1: execute initialization statement ① to complete the initialization of loop variables;
  • Step 2: execute the circular condition statement ② to see whether the value of the circular condition statement is true or false;
    • If true, perform step 3;
    • If false, the loop statement is terminated and the loop is no longer executed.
  • Step 3: execute loop body statement ③
  • Step 4: execute the iteration statement ④ and re assign the value to the loop variable
  • Step 5: start from step 2 again according to the new value of the loop variable

Syntax demonstration case 1: HelloWorld printed 10 times

public class ForDemo01 {
	public static void main(String[] args) {
    //The console outputs HelloWorld 10 times without using a loop
		System.out.println("HelloWorld");
		System.out.println("HelloWorld");
		System.out.println("HelloWorld");
		System.out.println("HelloWorld");
		System.out.println("HelloWorld");
		System.out.println("HelloWorld");
		System.out.println("HelloWorld");
		System.out.println("HelloWorld");
		System.out.println("HelloWorld");
		System.out.println("HelloWorld");
		System.out.println("-------------------------");

		//Improve with cycle, cycle 10 times
		//The defined variable starts from 10, and the cycle condition is < = 10
		for(int x = 1; x <= 10; x++) {
			System.out.println("HelloWorld"+x);
		}
	}
}

Grammar demonstration case 2: printing 1-5 and 5-1

/*
 * Exercise: print 1-5 and 5-1 with the for statement
 */
public class ForTest01 {
	public static void main(String[] args) {
		//Original practice
		System.out.println(1);
		System.out.println(2);
		System.out.println(3);
		System.out.println(4);
		System.out.println(5);
		System.out.println("===============");
		
		//Improve with cycle
		for(int x=1; x<=5; x++) {
			System.out.println(x);
		}
		System.out.println("===============");
		
		//We have obtained the data of 1-5. How to obtain 5-1?
		for(int x=5; x>=1; x--){
			System.out.println(x);
		}
	}
}

Syntax demonstration case 3: find the sum of data between 1-5

/*
 * Exercise: find the sum of data between 1-5
 * 
 * analysis:
 * 		1.Define the summation variable, and the initialization value is 0
 * 		2.Get the data between 1-5 and implement it with a for loop
 * 		3.Add up the data obtained each time
 * 		4.Output summation variable
 */
public class ForTest02 {
	public static void main(String[] args) {
		//Define the summation variable, and the initialization value is 0
		int sum = 0;
		
		//Get the data between 1-5 and implement it with a for loop
		for(int x=1; x<=5; x++) {
			//Add up the data obtained each time
			//sum = sum + x;
			/*
			 * First time: sum = 0 + 1 = 1
			 * Second time: sum = 1 + 2 = 3
			 * Third time: sum = 3 + 3 = 6
			 * Fourth time: sum = 6 + 4 = 10
			 * Fifth time: sum = 10 + 5 = 15
			 */
			sum += x;
		}
		
		//Output summation result
		System.out.println("sum:" + sum);
	}
}

Syntax demonstration case 4: find the even sum between 1-100

/*
 * Exercise: find the even sum between 1-100
 * analysis:
 * 		1.Define the summation variable, and the initialization value is 0
 * 		2.Obtain the data between 1-100 and implement it with the for loop
 * 		3.Judge the obtained data to see if it is even
 * 			If so, add up
 * 		4.Output summation result
 */
public class ForTest03 {
	public static void main(String[] args) {
		//Define the summation variable, and the initialization value is 0
		int sum = 0;
		
		//Obtain the data between 1-100 and implement it with the for loop
		for(int x=1; x<=100; x++) {
			//Judge the obtained data to see if it is even
			if(x % 2 == 0) {
				sum += x;
			}
		}
		
		//Output summation result
		System.out.println("sum:"+sum);
	}
}

3.9 loop structure: while loop

1. Standard format of while loop statement:

while (Circular conditional statement①) {
    Loop body statement②;
}
while(true){
     Loop body statement;//If there is no statement jumping out of the loop in the loop body at this time, it is also an dead loop
}

be careful:

Loop condition in while must be of type boolean

Execution process:

  • Step 1: execute the loop condition statement ① to see whether the value of the loop condition statement is true or false;
    • If it is true, perform the second step;
    • If false, the loop statement is terminated and the loop is no longer executed.
  • Step 2: execute the loop body statement ②;
  • Step 3: after the execution of the circular body sentence, execute it again from step 1

2. while loop statement extension format:

Initialization statement①;
while (Circular conditional statement②) {
    Loop body statement③;
    Iterative statement④;
}

Execution process:

  • Step 1: execute initialization statement ① to complete the initialization of loop variables;
  • Step 2: execute the circular condition statement ② to see whether the value of the circular condition statement is true or false;
    • If true, perform step 3;
    • If false, the loop statement is terminated and the loop is no longer executed.
  • Step 3: execute loop body statement ③
  • Step 4: execute the iteration statement ④ and re assign the value to the loop variable
  • Step 5: start from step 2 again according to the new value of the loop variable

Traversal syntax of even cases: 100-1

int num = 2;
while(num<=100){
    System.out.println(num);
    num+=2;
}

Grammar demonstration case 2: interesting Origami

/*
 *	Exercise: Fun Origami
 * 	
 *	Title:
 *		The highest mountain in the world is Mount Everest. Its height is 8844.43 meters. If I have a large enough paper, its thickness is 0.1 mm.
 *		How many times can I fold it to the height of Mount Everest?
 */
public class WhileTest01 {
    public static void main(String[] args) {
		//Define a counter with an initial value of 0
		int count = 0;
		
		//Define paper thickness
		double paper = 0.1;
		
		//Define the height of Mount Everest
		int zf = 8844430;
		
		//Because you need to fold repeatedly, you need to use a loop, but you don't know how many times to fold. In this case, it is more suitable to use a while loop
		//The folding process stops when the paper thickness is greater than Everest, so the requirement to continue is that the paper thickness is less than the height of Everest
		while(paper <= zf) {
			//During the execution of the cycle, each time the paper is folded, the thickness of the paper should be doubled
			paper *= 2;
			
			//How many times is the accumulation performed in the loop folded
			count++;
		}
		
		//Print counter value
		System.out.println("Folding required:" + count + "second");
    }
}

3.10 cycle structure: do... while cycle

1. Standard format of do... while loop statement:

do {
    Loop body statement①;
} while (Circular conditional statement②);

be careful:

(1) Loop condition in while must be of type boolean

(2)do{}while(); There is a semicolon at the end

(3) The circular body sentence of do... While structure will be executed at least once, which is different from that of for and while

Execution process:

  • Step 1: execute the loop body statement ①;
  • Step 2: execute the circular condition statement ② to see whether the value of the circular condition statement is true or false;
    • If true, perform step 3;
    • If false, the loop statement terminates and the loop is no longer executed.
  • Step 3: after the execution of the loop condition statement, execute it again from the first step

2. do... while loop statement extension format:

Initialization statement①
do {
    Loop body statement②;
    Iterative statement③;
} while (Circular conditional statement④);

Execution process:

  • Step 1: execute initialization statement ① to complete the initialization of loop variables;
  • Step 2: execute the loop body statement ②;
  • Step 3: execute iteration statement ③ and re assign values to cyclic variables;
  • Step 4: execute the circular conditional statement ④ to see whether the value of the circular conditional statement is true or false;
    • If it is true, execute again from the second step according to the new value of the loop variable;
    • If false, the loop statement is terminated and the loop is no longer executed.

Syntax demonstration case 1: count the number of positive and negative numbers

	public static void main(String[] args) {
		java.util.Scanner input = new java.util.Scanner(System.in);
		
		int positive = 0;
		int negative = 0;
		int num;
		do{
			System.out.print("Please enter an integer (0) to end:");
			num = input.nextInt();
			if(num>0){
				positive++;
			}else if(num<0){
				negative++;
			}
		}while(num!=0);
		System.out.println("Positive number:" + positive + "Number, negative:" + negative +"individual");
	}

Exercise: guess the number

Randomly generate a number within 100 and guess the number game

Enter the number from the keyboard. If it is large, the prompt will be large. If it is small, the prompt will be small. If it is right, you will no longer guess, and count the total number of guesses

Tip: random number math random()

double num = Math. random();// Decimal of [0,1)

	public static void main(String[] args){
		//Randomly generate an integer within 100
		/*
		Math.random() ==> [0,1)Decimal of
		Math.random()* 100 ==> [0,100)Decimal of
		(int)(Math.random()* 100) ==> [0,100)Integer of
		*/
		int num = (int)(Math.random()* 100);
		//System.out.println(num);
		
		//Declare a variable to store the number of guesses
		int count = 0;
		
		java.util.Scanner input = new java.util.Scanner(System.in);
		int guess;//Promote scope
		do{
			System.out.print("Please enter an integer within 100:");
			guess = input.nextInt();
			
			//If you enter it once, it means you guessed once
			count++;
			
			if(guess > num){
				System.out.println("Big");
			}else if(guess < num){
				System.out.println("Small");
			}
		}while(num != guess);
		
		System.out.println("I guess:" + count+"second");
		
	}

3.11 differences between circular statements

  • Analysis from the perspective of cycle times
    • do... while loop executes the loop body statement at least once
    • for and while loops first determine whether the loop condition statement is true, and then decide whether to execute the loop body. At least execute the loop body statement zero times
  • Analysis from the life cycle of cyclic variables
    • The loop variable of the for loop is declared in for() and cannot be accessed after the loop statement ends;
    • While and do... The loop variables of the while loop are declared outside, so while and do... Can be used after the end of while;
  • How to choose
    • If there is an obvious demand for the number (range) of cycles to traverse, select the for loop
    • Traversal has no obvious demand for the number (range) of cycles, and the loop is a while loop
    • If the loop body sentence block is executed at least once, consider using the do... while loop
    • In essence: the three cycles can be converted to each other, and all of them can realize the function of cycle
  • The three cycle structures have four elements:
    • (1) Initialization expression of loop variable
    • (2) Cycle condition
    • (3) Modified iterative expression of cyclic variable
    • (4) Circular aspect sentence block

12.3 control statement

3.12.1 break

  • Usage scenario: terminate switch or current loop
    • In the select structure switch statement
    • In a loop statement
    • It is meaningless to leave the existence of the usage scenario

Grammar case demonstration 1: judge whether a number is a prime number

	public static void main(String[] args){
		java.util.Scanner input = new java.util.Scanner(System.in);
		System.out.print("Please enter a positive integer:");
		int num = input.nextInt();
		
		boolean flag = true;
		for (int i = 2; i <= Math.sqrt(num) ; i++) {
			if(num%i==0){
				flag = false;
				break;
			}
		}
		System.out.println(num + (flag?"yes":"no") + "prime number");
	}

Grammar case demonstration 2: Statistics of positive and negative numbers

	public static void main(String[] args) {
		java.util.Scanner input = new java.util.Scanner(System.in);
		
		int positive = 0;
		int negative = 0;
		while(true){
			System.out.print("Please enter an integer (0) to end:");
			int num = input.nextInt();
			if(num==0){
				break;
			}else if(num>0){
				positive++;
			}else{
				negative++;
			}
		}
		System.out.println("Positive number:" + positive + ",Negative number:" + negative);
	}

Syntax case demonstration 3: break exists in both switch and loop

===ATM=
1. Deposit
2. Withdrawal
3. Show balance
4. Quit
Please select:

	public static void main(String[] args){
		java.util.Scanner input = new java.util.Scanner(System.in);
		
		//Declare a variable to represent the balance
		double balance = 0.0;
		boolean flag = true;
		while(flag){
			System.out.println("=========ATM=======");
			System.out.println("\t1,deposit");
			System.out.println("\t2,withdraw money");
			System.out.println("\t3,Show balance");
			System.out.println("\t4,sign out");
			System.out.print("Please select:");
			int select = input.nextInt();
			
			switch(select){
				case 1:
					System.out.print("Amount of deposit:");
					double money = input.nextDouble();
					balance += money;
					break;
				case 2:
					System.out.print("Withdrawal amount:");
					money = input.nextDouble();
					balance -= money;
					break;	
				case 3:
					System.out.println("Current balance:" + balance);
					break;
				case 4:
					flag = false;
					break;//Can only end switch
			}
		}
	}

3.12.2 continue

  • Usage scenario: end this cycle and continue the next cycle
public static void main(String[] args) {
    for (int i = 1; i <= 10; i++) {
        //Demand: do not print multiples of 3
        if(i % 3 == 0){
            continue;
        }
        System.out.println(i);
    }
}

Exercise: print integers between 1 and 100, skip multiples of 7 and numbers ending in 7

	public static void main(String[] args){
		//Print integers between 1 and 100, skipping multiples of 7 and numbers ending in 7
		for(int i=1; i<=100; i++){
			if(i%7==0 || i%10==7){
				continue;
				//break;
			}
			System.out.println(i);
		}
	}

3.13 nested loops

  • The so-called nested loop means that the loop body of one loop is another loop. For example, there is also a for loop in the for loop, which is a nested loop. Total number of cycles = number of external cycles * number of internal cycles. Of course, three loops can be nested with each other arbitrarily.
  • Nested loop format:
for(Initialization statement①; Circular conditional statement②; Iterative statement⑦) {
    for(Initialization statement③; Circular conditional statement④; Iterative statement⑥) {
      	Loop body statement⑤;
    }
}

Syntax case demonstration 1: print a rectangle with 5 rows and 5 columns

	public static void main(String[] args){
		for (int i = 0; i < 5; i++) {
			for (int j = 0; j < 5; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG ngfjnau-1646830777366) (IMG / 1561789094346. PNG)]

Grammar case demonstration 2: Print 5 lines of right triangle

	public static void main(String[] args){
		for (int i = 0; i < 5; i++) {
			for (int j = 0; j <= i; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}

Grammar case demonstration: break and double loop

	//Print 5 lines of right triangles
	public static void main(String[] args){
		for (int i = 0; i < 5; i++) {
			for (int j = 0; j < 5; j++) {
				System.out.print("*");
				if(i==j){
					break;
				}
			}
			System.out.println();
		}
	}

Topics: Java JavaSE