JAVA branch structure switch structure for loop

Keywords: Java R Language

1 branch structure

Although the program with sequential structure can solve the problems of calculation and output
But you can't judge and choose. For the problem of making judgment before selection, we should use the branch structure

1.2 form

1.3.1 exercise: Commodity discount cases

Create package: cn.tedu.basic
Create class: TestDiscount.java
Demand: receive the original price entered by the user. 10% off for 1000; 20% off for 2000; 50% off for over 5000

package cn.tedu.basic;

import java.util.Scanner;

/**Demand: receive the original price entered by the user, 10% off for 1000, 20% off for 2000 and 5% off for 5000*/
public class TestDiscount {
	public static void main(String[] args) {
		//1. Prompt the user to enter the original price
		System.out.println("Please enter the original price:");
		//2. Receive the original price entered by the user
		double price = new Scanner(System.in).nextDouble();                     
		//3. Calculate the discounted price
		//3.1 define variables to save discounted prices
		double count = price;//The initial value is the original price of the commodity
		//3.2 judge the user's discount segment and discount
		if(price >= 5000) {//Over 5000
			count = price *0.5;//50% off
		}else if(price >= 2000) {//Over 2000
			count = price * 0.8;//20% off
		}else if(price >= 1000) {//Over 1000
			count = price *0.9;//10% off
		}
//		if(1000 <= price && price< 2000) {
//			count = price *0.9;
//		}else if(2000 <= price && price < 5000) {
//			count = price * 0.8;
//		}else if(price >= 5000) {
//			count = price *0.5;
//		}
		//3.3 output the price actually paid by the user
		System.out.println("You should actually pay:"+count);
	}
}

 

1.3.2 exercise: count the cases of students' scoring segments

package cn.tedu.basic;

import java.util.Scanner;

/*This category is used to judge the grades of students*/
public class TestScore {
	public static void main(String[] args) {
		//1. Prompt and receive students' scores
		System.out.println("Please enter your score:");
		int score = new Scanner(System.in).nextInt();
		/*90 Excellent with score or above
		 *80-89 good
		 *70-79 secondary
		 *60-69 pass
		 *60 Fail with score or below */
		
		/**In order to enhance the robustness of the program, if the data entered by the user does not comply with the rules, it will end*/
		if(score <0 || score >100 ) {
			System.out.println("The input data is illegal, please re-enter!!!");
		}else {
			//2. Judge the segment of the score and output the result
			if(score >= 90) {//Greater than 90
				System.out.println("Excellent!");
			//}else if(score>=80 && score <=89) {
			}else if(score>=80) {//[80,90)
				System.out.println("Good!");
			}else if(score>=70) {//[70,80)
				System.out.println("Medium!");
			}else if(score>=60) {//[60,70)
				System.out.println("Pass!");
			}else {//Less than 60
				System.out.println("fail,");
			}
		}	
	}
}

2 switch structure

2.1 general

The switch case statement is used to judge whether a variable is equal to a value in a series of values. Each value is called a branch.
When a case is established, it penetrates all cases backward from this case, including default, until the program ends or encounters a break

2.2 form

2.3 exercise: number matching

Create package: cn.tedu.basic
Create class: TestSwitch.java

package cn.tedu.basic;
/*This class is used to practice the switch structure*/
/**Summary:
 * 1.Type of variable a byte short char int String
 * 2.Compare the value of variable a with the value after case in turn. If break is not added,
 *        It penetrates all case s backward, including default
 * 3.If the default "minimum guarantee option" is set and no case matches, execute default
 * 4.break And default are optional. Whether to add or not depends on the specific business
 * */
public class TestSwitch {
	//1. Create the entry function main of the program
	public static void main(String[] args) {
		//2. Define a variable
		int a = 19;
		//3. Complete the test of switch structure
		switch(a) {
			case 1 : System.out.println(1);break;
			case 2 : System.out.println(2);break;
			case 3 : System.out.println(3);break;
			case 4 : System.out.println(4);break;
			case 5 : System.out.println(5);break;
			default : System.out.println(0);
		}		
	}
	
}


 

2.4 exercise: String type in Switch

Using class: TestSwitch.java

package cn.tedu.basic2;
/**This class is used to test switch structure 2*/
public class TestSwitch2 {
	public static void main(String[] args) {
		String day = "Friday";
		switch(day) {
			case "Monday" : System.out.println("Sichuan hot pot on Monday");break;
			case "Tuesday" : System.out.println("Eat Qiqihar barbecue on Tuesday");break;
			case "Wednesday" : System.out.println("Eat Xinjiang mutton kebabs on Wednesday");break;
			case "Thursday" : System.out.println("Eat Yangcheng Lake hairy crabs on Thursday");break;
			case "Friday" : System.out.println("Lanzhou Ramen on Friday");break;
			case "Saturday" : System.out.println("Eat Nanchang mixed flour on Saturday");break;
			case "Sunday" : System.out.println("Eat Wuhan lotus root soup on Sunday");break;
			default : System.out.println("Eat what you want~");
		}
	}
}

2.5 precautions for switch structure
1. The variable types in the switch statement can be byte, short, int, char and string (supported after jdk1.7)
2. A switch statement can have multiple case statements
3. Each case is followed by a value and colon to be compared, and the data type of this value must be consistent with the data type of the variable
4. When the variable value is equal to the case statement value, start to execute the contents of the case statement. After execution, it will judge whether there is a break in this line of code. If so, end the execution. If not, it will continue to execute backward to penetrate all cases, including default
5. A switch statement can contain a default branch, which is usually written at the end of the switch statement
6. If the case before default has a break, default will not execute

3 cycle structure

3.1 for Overview

Loop structure refers to a program structure that needs to execute a function repeatedly in the program.
It determines whether to continue to perform a function or exit the loop according to the conditions in the loop body.
According to the judgment conditions, the loop structure can be subdivided into the loop structure of judgment before execution and the loop structure of execution before judgment.

3.2 for form

3.3 execution sequence of for loop

We only wrote a printed sentence, why did we print multiple numbers?
I hope the following figure can help you understand the execution sequence of the for loop

3.4 exercise: print 100 slogon / print 0 to 10 / print 10 to 0 / print 8,888,

package cn.tedu.basic;
/**This class is used to test the loop structure for loop*/
public class TestFor {
	public static void main(String[] args) {
		//Requirements: print your manifesto 100 times
		//For (start condition; loop condition; change condition) {loop body;}
		for(int i = 1;i<=100;i++) {
			System.out.println("It's not that without that condition, it's over! ");
		}
		//Requirements: print 0 to 10
		//For (start condition; loop condition; change condition) {loop body;}
		//0 1 2 3 4 5 6 7 8 9 10
		//Where to start: 0
		//Where to end: 10
		//How to change: + 1++
		for(int i = 0;i<=10;i++) {
			System.out.println(i);
		}
		System.out.println("**********************");
		//Requirements: print 10 to 0
		//10 9 8 7 6 5 4 3 2 1 0
		//Where to start: 10
		//Where to end: 0
		//How to change: - 1--
		//For (start condition; loop condition; change condition) {loop body}
		for(int i = 10 ;i >= 0;i--) {
			System.out.println(i);
		}
		//Requirements: print 8, 888,
		//8 88 888 8888
		//Where to start: 8
		//Where to end: 8888
		//How to change: * 10 + 8
		for(int i =8 ; i <= 8888 ; i=i*10+8) {
			System.out.print(i+",");//print() is used, and there is no line break after printing
		}
	}
}

 

3.5 exercise: find the sum of elements within [1100], the sum of even numbers, and the number of even numbers

package cn.tedu.basic;
/*This class is used to test the for loop structure 2*/
public class TestFor2 {
	public static void main(String[] args) {
		//m1();
		//m2();
		m3();
	}
	/*Demand: find the number of all even numbers within 1-100*/
	private static void m3() {
		//1. Define the number of variables used to store even numbers
		int count = 0;
		//2. Create a cycle and cycle the numbers in the range of 1-100 in turn
		for(int i = 1;i<101;i++) {
			//3. Filter out the even number to be counted
			if(i % 2 ==0) {//This indicates that this is an even number
				//4. Accumulate even numbers
				//count = count +1;
				count++;
				//++count;
			}
		}
		//5. Print the number of final statistics
		System.out.println(count);
	}
	/*Requirement: find the sum of all even numbers within 1-100*/
	private static void m2() {
		//1. Define variables to save the final summation results
		int sum = 0;
		//2. Create a cycle and cycle the numbers in the range of 1-100 in turn
		for(int i = 1;i <101;i++) {
			//3. Filter out even numbers to be accumulated
			if(i%2 == 0) {
			//if(i%2 == 1) {/ / filter odd numbers
				//4. If you can come in, it means that it is even and cumulative
				sum = sum +i;
			}
		}
		//5. After the for loop ends, print the sum of all even numbers
		System.out.println(sum);
	}
	/*Requirement: find the sum of all numbers within 1-100*/
	private static void m1() {
		//1. Define a variable to save the summation result
		int sum = 0;
		//2. Create a cycle and cycle the numbers in the range of 1-100 in turn
		for(int i = 1;i<=100;i++) {
			//3. Add the numbers in this cycle to the final result
			sum = sum + i;
		}
		//4. Print the result of final accumulation
		System.out.println(sum);
	}
}

 

Posted by kristianblom on Sun, 07 Nov 2021 18:51:47 -0800