day03 switch & loop statement

Keywords: Java REST less

1. switch statement

1.1 branch statement switch statement

  • format

    switch (expression){
    	case 1:
    		Statement body 1;
    		break;
    	case 2:
    		Statement body 2;
    		break;
    	...
    	default:
    		Statement body n+1;
    		break;
    }
    
  • Execution process:

    • First calculate the value of the expression
    • Secondly, compare with case in turn. Once there is a corresponding value, the corresponding statement will be executed. In the process of execution, the break will end.
    • Finally, if all case s don't match the value of the expression, the body part of the default statement is executed and the program ends.

1.2 switch case - weight loss plan

  • Requirement: input the weeks by keyboard to display the weight loss activities today
Monday: running  
Tuesday: swimming  
Wednesday: walk slowly  
Thursday: cycling
 Friday: Boxing  
Saturday: mountain climbing  
Sunday: have a good meal 
  • Example code:
public static void main(String[] args){
		// 1. Input weekly data by keyboard and receive with variable
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter");
		int week = sc.nextInt();
		// 2. Multi situation judgment, implemented by switch statement
		switch(week){
			// 3. Output the corresponding weight loss plan in different case s
			case 1:
				System.out.println("run");
				break;
			case 2:
				System.out.println("Swimming");
				break;
			case 3:
				System.out.println("Walk slowly");
				break;
			case 4:
				System.out.println("Cycling");
				break;
			case 5:
				System.out.println("Boxing");
				break;
			case 6:
				System.out.println("Mountain climbing");
				break;
			case 7:
				System.out.println("Have a good meal");
				break;
			default:
				System.out.println("Your input is wrong");
				break;
		}
	}
}

1.3 switch statement case penetration

  • Overview: if case omits break statement in switch statement, case penetration will start
  • Demand: input weeks by keyboard, output workdays, rest days (1-5) workdays, and (6-7) rest days
  • Example code:
/*
case How does penetration occur?
		
		If case omits break statement in switch statement, case penetration will start
		
		Phenomenon:
			When case penetration starts, subsequent cases will not have matching effect, and internal statements will be executed
			It doesn't end until you see a break, or the entire switch statement is executed.
*/
public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter the number of weeks:");
		int week = sc.nextInt();
		
		switch(week){
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
				System.out.println("working day");
				break;
			case 6:
			case 7:
				System.out.println("Rest Day");
				break;
			default:
				System.out.println("Your input is wrong");
				break;
		}
	}	
}

2. for loop

2.1 loop statement for loop

  • Cycle:

    The loop statement can execute a certain section of code repeatedly under the condition that the loop condition is met. This section of code that is executed repeatedly is called the loop body statement. When the loop body is executed repeatedly, it is necessary to modify the loop judgment condition to false when appropriate, so as to end the loop. Otherwise, the loop will continue to execute and form a dead loop.

  • for loop format:

for (initialization statement; condition judgment statement; condition control statement){
	Loop body statement;
}
  • Format explanation:

    • Initialization statement: used to indicate the start state when the loop is opened. In short, it is what the start state of the loop is
    • Condition judgment statement: it is used to indicate the condition of repeated execution of a loop. In short, it is used to determine whether the loop can be executed all the time
    • Loop body statement: it is used to represent the content of repeated loop execution. In short, it is the thing of repeated loop execution
    • Conditional control statement: used to indicate the content of each change in the execution of a loop. In short, it controls whether the loop can be executed
  • Execution process:

    ① Execute initialization statement

    ② Execute conditional judgment statement to see whether the result is true or false

    If false, the loop ends

    If true, continue

    ③ Execute loop body statement

    ④ Execute conditional control statement

    ⑤ Go back to ② continue

2.2 for loop case - output data 1-5 and 5-1

  • Requirements: output 1-5 and 5-1 data in the console
  • Example code:
public class ForTest01 {
    public static void main(String[] args) {
		//Requirements: output data 1-5
        for(int i=1; i<=5; i++) {
			System.out.println(i);
		}
		System.out.println("--------");
		//Requirements: output data 5-1
		for(int i=5; i>=1; i--) {
			System.out.println(i);
		}
    }
}

2.3 for cycle case - find 1-5 data and

  • Requirement: sum the data between 1-5 and output the sum result on the console
  • Example code:
public class ForTest02 {
    public static void main(String[] args) {
		//The final result of summation must be saved. A variable needs to be defined to save the result of summation. The initial value is 0
		int sum = 0;
		//The data from 1 to 5 is completed with a circular structure
		for(int i=1; i<=5; i++) {
			//Write recurring things into the loop structure
             // What happens repeatedly here is to add data i to the variable sum that holds the final sum
			sum += i;
			/*
				sum += i;	sum = sum + i;
				The first time: sum = sum + i = 0 + 1 = 1;
				The second time: sum = sum + i = 1 + 2 = 3;
				The third time: sum = sum + i = 3 + 3 = 6;
				The fourth time: sum = sum + i = 6 + 4 = 10;
				The fifth time: sum = sum + i = 10 + 5 = 15;
			*/
		}
		//When the loop is finished, the final data will be printed out
		System.out.println("1-5 The sum of the data between is:" + sum);
    }
}
  • Key points:
    • In the future, if there is a word "sum", please immediately associate the sum variable with it
    • The definition position of the summation variable must be outside the loop. If it is inside the loop, the calculated data will be wrong

2.4 for cycle case - find 1-100 even sum

  • Requirement: find the even sum between 1-100, and output the sum result in the console}
  • Example code:
public class ForTest03 {
    public static void main(String[] args) {
		//The final result of summation must be saved. A variable needs to be defined to save the result of summation. The initial value is 0
		int sum = 0;
		//The sum of 1-100 data is almost the same as the sum of 1-5 data, only the ending conditions are different
		for(int i=1; i<=100; i++) {
			//For the even sum of 1-100, it is necessary to add restrictions on the sum operation to determine whether it is even
			if(i%2 == 0) {
				sum += i;
			}
		}
		//When the loop is finished, the final data will be printed out
		System.out.println("1-100 The even sum between is:" + sum);
    }
}

2.5 for cycle case - number of daffodils

  • Requirement: output all "narcissus number" on the console
  • Explanation: what is narcissus number?
    • The number of Narcissus refers to a three digit number. The sum of the cubes of one digit, ten digit and hundred digit is equal to the original number
      • For example, 153 3 * 3 * 3 + 5 * 5 * 5 + 1 * 1 * 1 = 153
  • Ideas:
    1. Get all three digits and prepare for filtering. The minimum three digits are 100 and the maximum three digits are 999. Use for loop to get
    2. Obtain each three digit digit digit, ten digit, hundred digit, and make if statement to determine whether it is the number of daffodils
  • Sample code
public class ForTest04 {
    public static void main(String[] args) {
		//Output all the number of Narcissus must be used to cycle, traverse all three digits, three digits from 100 to 999
		for(int i=100; i<1000; i++) {
			//Get the value on each of the three digits before calculating
			int ge = i%10;
			int shi = i/10%10;
			int bai = i/10/10%10;
			
			//The judgment condition is to take out each value in three digits, and calculate whether the sum of cubes is equal to the original number
			if(ge*ge*ge + shi*shi*shi + bai*bai*bai == i) {
				//Output the number that meets the conditions is the number of Narcissus
				System.out.println(i);
			}
		}
    }
}

2.6 for cycle case - print 2 Narcissus per line (Statistics)

  • Requirement: output all "narcissus number" on the console, and print 2 for each line
  • Example code:
public class Demo6For {
	/*
		Requirement: output all "narcissus number" on the console, and print 2 for each line

		System.out.print (Print content); do not wrap after printing
		System.out.println(Print content); wrap after printing

		analysis:
			
			1. Define the variable count to save the quantity of "printed". The initial value is 0
			2. In the process of determining and printing the number of Narcissus, the spaces are spliced, but the lines are not wrapped. After printing, the count variable + 1 is used to record the number of printed Narcissus
			3. After each count variable + 1, judge whether it has reached the multiple of 2. If yes, line feed.

	*/
	public static void main(String[] args){
		// 1. Define the variable count to save the quantity of "printed". The initial value is 0
		int count = 0;
		for(int i = 100; i <= 999; i++){
			int ge = i % 10;
			int shi = i / 10 % 10;
			int bai = i / 10 / 10 % 10;
			
			if(	(ge*ge*ge + shi*shi*shi + bai*bai*bai) == i){
				//  2. In the process of determining and printing the number of Narcissus, splice the spaces, but do not wrap the lines, and after printing, make the count variable + 1 to record the printed quantity
				System.out.print(i + " ");
				count++;
				// 3. After each count variable + 1, judge whether it has reached the multiple of 2. If yes, line feed
				if(count % 2 == 0){
					System.out.println();
				}
			}
		}
	}
}
  • Key points:
    • In the future, if the demand has statistics xxx, please think of the counter variable first
    • The position defined by the counter variable must be outside the loop

3. while cycle

3.1 loop statement - while loop

  • while loop full format:

    Initialization statement;
    while (conditional statement){
    	Loop body statement;
        Conditional control statement;
    }
    
  • while loop execution process:

    ① Execute initialization statement

    ② Execute conditional judgment statement to see whether the result is true or false

    If false, the loop ends

    If true, continue

    ③ Execute loop body statement

    ④ Execute conditional control statement

    ⑤ Go back to ② continue

  • Example code:

public class WhileDemo {
    public static void main(String[] args) {
        //Requirement: output "HelloWorld" 5 times in the console
		//for loop implementation
		for(int i=1; i<=5; i++) {
			System.out.println("HelloWorld");
		}
		System.out.println("--------");
		//while loop implementation
		int j = 1;
		while(j<=5) {
			System.out.println("HelloWorld");
			j++;
		}
    }
}

3.2 while cycle case - Everest

  • Demand: the highest mountain in the world is Mount Everest (8844.43m = 8844430mm). If I have a piece of paper large enough, its thickness is 0.1mm. How many times can I fold it to the height of Mount Everest?
  • Example code:
public class WhileTest {
    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 Everest
		int zf = 8844430;
		//Because you need to fold repeatedly, you need to use a loop, but you don't know how many times you want to fold. In this case, it is more suitable to use a while loop
		//In the process of folding, when the paper thickness is greater than the Everest, it stops, so the requirement to continue is that the paper thickness is less than the Everest height
		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 has the accumulation been performed in the loop
			count++;
		}
		//Print counter value
		System.out.println("Need to fold:" + count + "second");
    }
}

4. Cycle details

4.1 loop statement - dowhile loop

  • Full format:

    Initialization statement;
    do {
    	Loop body statement;
    	Conditional control statement;
    }While (conditional statement);
    
  • Execution process:

    ① Execute initialization statement

    ② Execute loop body statement

    ③ Execute conditional control statement

    ④ Execute conditional judgment statement to see whether the result is true or false

    If false, the loop ends

    If true, continue

    ⑤ Go back to ② continue

  • Example code:

public class DoWhileDemo {
    public static void main(String[] args) {
        //Requirement: output "HelloWorld" 5 times in the console
		//for loop implementation
		for(int i=1; i<=5; i++) {
			System.out.println("HelloWorld");
		}
		System.out.println("--------");
		//do...while loop implementation
		int j = 1;
		do {
			System.out.println("HelloWorld");
			j++;
		}while(j<=5);
    }
}

4.2 difference of three cycles

  • The difference of three cycles
    • for loop and while loop first determine whether the condition is true, and then decide whether to execute the loop body (judge first and then execute)
    • do… The while loop executes the body of the loop once, and then judges whether the condition is true and whether to continue to execute the body of the loop (execute first and then judge)
  • The difference between for loop and while
    • The auto increment variable controlled by the conditional control statement cannot be accessed again after the for loop is finished because it belongs to the syntax structure of the for loop
    • The auto increment variable controlled by the conditional control statement does not belong to its syntax structure for the while loop. After the end of the while loop, the variable can still be used
  • Three forms of infinite loop
    1. for( ; ; ){}
    2. while(true){}
    3. do {} while(true);

4.3 dead cycle

  • Loop format

    for Dead cycle format :
    for(;;){
    
    }
    
    while Loop format :
    
    while(true){
    
    }
    
    do..while Loop format :
    
    do{
    
    }while(true);
    
  • Dead cycle case

/*
	Question: is there an application scenario for the loop?
		
				For example: enter an integer between 1-100
				
				Concern: keyboard input is operated by users, and users may have some misoperation
		
*/
public static void main(String[] args) {
    /*
		for(;;){
			System.out.println("I can't stop;
		}
		*/

    /*
		while(true){
			System.out.println("I can't stop;
		}
		*/

    do{
        System.out.println("I can't stop~");	
    }while(true);

    System.out.println("See if I can be executed?~");	// Unreachable statement
}
}

4.4 jump control statement

  • Jump control statement (break)
    • Jump out of loop, end loop
  • Jump control statement (continue)
    • Skip this cycle and continue the next cycle
  • Note: continue can only be used in loops!
public class Demo1Continue {
	/*
		continue : Skip the execution of the content of a loop
		
		Note: use is based on condition control and used inside the loop
		
		Demand: simulate the process of elevator ascending from floor 1 to floor 24, floor 4 does not stop
	*/
	public static void main(String[] args){
		for(int i = 1; i <= 24; i++){
			if(i == 4){
				continue;
			}
			System.out.println(i + "The floor is here~");
		}
	}
	
}
public class Demo2Break {
	/*
		break : Terminate execution of loop body content
		Note: use is condition based
				break Statements can only be used in loops and switch es
				
		Demand: simulate working from 20 to 80 and retiring at 60
	*/
	public static void main(String[] args){
		for(int i = 20; i <= 80; i++){
			if(i == 60){
				break;		// End the cycle
			}
			System.out.println(i + "I'm working");
		}
	}
	
}
import java.util.Scanner;

public class Test {
	/*
		Requirement: after the program is running, the user can query the weight loss plan corresponding to the week for many times until entering 0, and the program is finished
		
		Step:
			
			1. It is unclear how many times the user operates and uses the business logic of the dead cycle package
			2. When matching to 0, use break to end the loop

	*/
	public static void main (String[] args){
		
		lo:while(true){
			System.out.println("Please enter the number of weeks you want to view:");
			System.out.println("(If you do not need to continue to view,Please enter 0 to exit the program)");
			
			// 1. Input weekly data by keyboard and receive with variable
			Scanner sc = new Scanner(System.in);
			int week = sc.nextInt();
			// 2. Multi situation judgment, implemented by switch statement
			switch(week){
				// 3. Output the corresponding weight loss plan in different case s
				case 0:
					System.out.println("Thank you for your use");
					break lo;
				case 1:
					System.out.println("run");
					break;
				case 2:
					System.out.println("Swimming");
					break;
				case 3:
					System.out.println("Walk slowly");
					break;
				case 4:
					System.out.println("Cycling");
					break;
				case 5:
					System.out.println("Boxing");
					break;
				case 6:
					System.out.println("Mountain climbing");
					break;
				case 7:
					System.out.println("Have a good meal");
					break;
				default:
					System.out.println("Your input is wrong");
					break;
			}
		}
		
		
	}
}

5. Random

5.1 Random number generated by random

  • summary:

    • Random, like Scanner, is a good API provided by Java. It provides the function of generating random numbers internally
      • The API will be explained in detail in the following courses. Now it can be simply understood as the code that Java has written
  • Use steps:

    1. Import package

      import java.util.Random;

    2. create object

      Random r = new Random();

    3. Generate random number

      int num = r.nextInt(10);

      Explanation: 10 represents a range. If you write 10 in parentheses, the generated random number is 0-9. If you write 20 in parentheses, the random number of parameters is 0-19

  • Example code:

import java.util.Random;

public class Demo1Random {
	/*
		Random : Generate random number
		
		1. Guide Package: import java.util.Random ;
				    The action of the leading package must appear above the class definition

		2. Create object: Random r = new Random();
					In the above format, r is the variable name, which can be changed, and others are not allowed to change

		3. Get random number: int number = r.nextInt(10); / / get data range: [0,10) includes 0, excluding 10
					In the above format, number is the variable name, which can be changed, and number 10 can be changed. Nothing else is allowed to change
		
		Demand: generate random numbers between 1-10
	*/
	public static void main(String[] args){
		// 2. Create object
		Random r = new Random();
		
		for(int i = 1; i <= 10; i++){
			// 3. Obtain random number
			int num = r.nextInt(10) + 1;		// 1-10
			System.out.println(num);
		}
		
		
		
	}
}

5.3 Random exercise - guessing numbers (application)

  • Requirements:

    The program automatically generates a number between 1 and 100. Use the program implementation to guess the number?

    When guessing wrong, give corresponding prompt according to different situations

    A. If the guessed number is larger than the real number, it indicates that the guessed data is larger

    B. If the number you guessed is smaller than the real number, you will be prompted that the number you guessed is smaller

    C. If the number you guessed is equal to the real number, congratulations

  • Example code:

import java.util.Scanner;
import java.util.Random;

public class Test {
	/*
		Requirement: the program automatically generates a number between 1 and 100. Use the program implementation to guess the number?
			When guessing wrong, give corresponding prompt according to different situations
			If the guessed number is larger than the real number, it indicates that the guessed data is larger
			If the number you guessed is smaller than the real number, you will be prompted that the number you guessed is smaller
			If the number you guessed is equal to the real number, congratulations
		
		1. Prepare Random and Scanner objects to generate Random numbers and keyboard entries, respectively
		2. Use Random to generate a number between 1 and 100 as the number to guess
		3. Input the data guessed by the user by keyboard
		4. Use the entered data (user guessed data) and the random number (to guess data) to compare, and give a prompt
		
		5. The above content needs to be carried out many times, but it can't be estimated how many times the user input can be guessed correctly. Use while(true) to loop the package
		6. After guessing right, break is over

	*/
	public static void main(String[] args){
		// 1. Prepare Random and Scanner objects to generate Random number and keyboard input respectively
		Random r = new Random();
		Scanner sc = new Scanner(System.in);
		// 2. Use Random to generate a number between 1-100 as the number to guess
		int randomNum = r.nextInt(100) + 1;
		
		// 5. The above content needs to be carried out many times, but it can't be estimated that the user can guess correctly several times. Use while(true) to loop the package
		while(true){
			// 3. Input the data guessed by the user by keyboard
			System.out.println("Please input your guess data:");
			int num = sc.nextInt();
			// 4. Use the entered data (user guessed data) and random number (to guess data) to compare, and give a prompt
			if(num > randomNum){
				System.out.println("Guess big");
			}else if(num < randomNum){
				System.out.println("Guess small");
			}else{
				// 6. After guessing right, break is over
				System.out.println("congratulations,You guessed it");
				break;
			}
		}
		
		System.out.println("Thank you for your use");
		
	}
}

Posted by gobbly2100 on Wed, 17 Jun 2020 23:56:25 -0700