Branch statements in Java

Author: Han Ru

Company: Procedural Coffee (Beijing) Technology Co., LTD

Procedure: IT professional skills evaluation platform

Website: www.chengxuka.com

task

1. Execution structure of the program 2. Branch statement 3Copy the code

1. The execution structure of the program

The execution of a program consists of the following three structures, which are sequential by default. It’s line by line.

  1. Sequential structure
  2. Choose structure
  3. Loop structure
1.1 Sequence Structure
The program executes code line by line from top to bottom, without judgment or relay. The code snippet is executed1To execute the code snippet2.Copy the code

1.2 Branch Structure
Selectively executes or skips specified codeCopy the code

1.3 Cyclic structure
If the loop condition is met, some code will be executed more than once.Copy the code

Two, branch structure

In this section we’ll focus on branching. In the Java language, there are two syntax supports for branching, an if statement and a switch statement. Let’s look at the if statement first.

2.1 if statement

The if statement can be used in four ways:

  • If (condition) {… }

  • If (condition) {… } else {… }

  • If (condition) {… }else if(condition){… } else {… }

  • If (condition){if(condition){… } } else {… }

2.1.1 Simple IF statement
if (True or false */) {
    // If the condition results in true, execute the statement within braces
}
/* If = false; /* if = false; /* if = false
Copy the code

Flow chart:

Example code:

import java.util.Scanner;

public class Demo22If {

	public static void main(String[] args) {
		/* * if (true or false) {// If (true or false) { If true, execute the statement inside the braces. If false, execute the statement outside the braces. * */
		// 1. Define a score. If 60 or greater, print a pass
		int score = 88;
		if (score >= 60) {
			// If the condition results in true, execute the statement within braces
			System.out.println("Pass...");
		}
		
		System.out.println("over....");
		
		//2. Define an integer. If greater than 0, print a positive number
		
		System.out.println(Please enter an integer:);
		Scanner scan =new Scanner(System.in);
		
		int num = scan.nextInt();

		
		if(num > 0){
			System.out.println(num + "Is a positive number.");
			
		}
		
		System.out.println("over........."); }}Copy the code

Running result:

Java scores greater than 60 are rewarded with a candy bar

	// A simple if statement:
	// If the score is greater than 60, a reward will be given
	int score = 10;
	if(score>60){
		System.out.println("Give me a candy.");
	}	
Copy the code

Example code: Java scores greater than 98, and Html scores greater than 80, the teacher awarded him; Or a Java score equal to 100 and an Html score greater than 70.

if((score1 >98 && score2 > 80 ) || ( score1 == 100 && score2 > 70)) {/ / reward
}
Copy the code
2.1.2 the if – else statements
if (True or false */) {
    // The true statement body
} else {
    // False body
}
/* Execution flow: When the code runs to the if-else structure, it first checks whether the condition after the if is true. If true, it executes the curly braces and the true body. If false, it executes the else curly braces and the false body */
Copy the code

Example code:

import java.util.Scanner;

public class Demo23IfElse {

	public static void main(String[] args) {
		/* * if (true or false) {else {* / false} * * if (true or false) {else {* / false} * * If it is true, it is true. If it is true, it is true. If it is false, it is false
			
		int score = 88;
		
		if(score >= 60){
			System.out.println(score+", pass");
		}else{
			System.out.println(score+",不及格。。。");
		}
		
		System.out.println("over...");
		// If you are male, go to the men's room; otherwise, go to the women's room
		
		/* * Extension: Compare values * basic data types: ==, compare values for equality * 8 basic types * * Reference data types: equlas(), compare values for equality * String */
		System.out.println("Please enter your gender:");
		Scanner scan = new Scanner(System.in);
		String sex = scan.next();
		if("Men".equals(sex)){
			System.out.println(sex+"Go to the men's room.");
		}else{
			System.out.println(sex+"Go to the ladies' room.");
		}
		
		
		System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
		
		
		char sex2 = 'male';
// int sex3 = 1; // One male and two female
// boolean sex4 = true; // True male, false female
		
		if(sex2 == 'male'){
			System.out.println("To the men's room.");
		}else{
			System.out.println("Go to the ladies' room..."); }}}Copy the code

Running result:

Extension content: More often than not, pay attention to the data types.

Comparison values for basic data types use the == operator.

Reference type comparison practical equlas() method. Strings are reference data, so you need to use equals() for comparison. It is also recommended that literal constants be written in front: “wang er dog “.equals(name).

Example: Always 18 if you’re a boy, always 16 if you’re not.

		// If you are a boy, you will always be 18
		// If it is a girl, it is always 16 years old
		char c = 'woman';
		if(c == 'male') {// Boolean the result is true in if or else in else
			System.out.println("Always 18.");
		}else{
			System.out.println("16 forever.");
		}
Copy the code

Example: Buying lottery tickets

If I win 5 million in sports lottery, I will buy a car, buy a house and travel to Africa

If you don’t win, keep buying.

public static void main(String[] args){
		//1 Create the input object
		Scanner input=new Scanner(System.in);
		/ / 2
		System.out.println("Five million? Y/N");
		String answer=input.next();
		/ / 3
		if("y".equals(answer)){  // Use equals () to determine the string
			System.out.println("Buying a house, buying a car, traveling to Africa...");	
		}else{
			System.out.println("Keep buying...."); }}Copy the code

Note: String determination uses equals

Example: enter four digits of the membership number of the hundred digits is equal to the random number generated for the lucky member, prompt congratulations on your winning, otherwise did not win.

Int random=(int)(math.random ()*10); / / random number

Note: Math. The random (); Produces a number between 0 and 1, including 0 without 1

public static void main(String[] args){
		// Create an Input object
		Scanner input=new Scanner(System.in);
		/ / hint
		System.out.println("Please enter the 4-digit membership number :");
		int member=input.nextInt();

		/ / one hundred
		int bai=member/100%10;
		int ran=(int)(Math.random()*10);   //Math.random(); Produces a number between 0 and 1, including 0 without 1
		if(bai==ran){
			System.out.println("Won the lottery.... Take a trip.");
		}else{
			System.out.println("Work hard..."); }}Copy the code

The String comparison method is equlas(). The basic data type is ==.

2.1.3 Multiple if statements

The if… Else if… The else statement is used to judge multiple conditions and perform a variety of different processes

if(judgment condition)1) {execute the statement1; }else if(judgment condition)2) {execute the statement2; }...else if(judge statement n) {execute statement n; }else{execute statement n+1;
}
Copy the code

Class drawing:

Example code:

public class Demo24MulIf {

	public static void main(String[] args) {
		/ * * multiple if statement: a commonplace * if conditions (1) {* / / conditions 1 was established, the implementation of the code, the code is behind the does not perform the * *} else if (2) {* / / condition 1, condition 2, execution code. Here. * *}else if(condition 3){* / * *}... * /
		
		String sex = "Monkey";
		
		if("Men".equals(sex)){
			System.out.println("Men's room."+sex);
		}else if("Women".equals(sex)){
			System.out.println("Ladies' room."+sex);
		}else{
			System.out.println("I don't know, maybe not the toilet.");
		}
		
		System.out.println("over.."); }}Copy the code

Running result:

Example: If the score is greater than 90 and the boy gets a girlfriend, if the score is greater than 90 and the girl gets a boyfriend, otherwise…

	char c = 'woman';
	int score = 10;	
	if(score>90 && c=='male'){
			System.out.println("Send me a girlfriend.");	
	}else if(score>90 && c=='woman'){
			System.out.println("Send me a boyfriend.");
	}else if(score<=1){
			System.out.println("You're a badass.");
	}
Copy the code

Computer exercises:

I want to buy a car, which car depends on how much money I have in the bank

If I have more than 5 million in savings, I’ll buy a Porsche

Otherwise, if MY savings exceed 1 million, I will buy a BMW

Otherwise, if I have more than half a million in savings, I’ll buy the Passat

Otherwise, if my deposit exceeds 100,000, I will buy QQ

Otherwise, if I have less than $100,000, I buy Giant

2.1.4 Nested if statements
if(conditions1) {

      if(conditions2) {code block1

      } else{code block2}}else{code block3

}

Copy the code

Example code:

public class Demo25If {

	public static void main(String[] args) {
		// Given a gender and age, judge whether you can get married
		// Male: not less than 22 years old
		// Female: not less than 20 years old
		
		char sex = 'male';
		
		int age = 23;
		
		if(sex == 'male') {// Male, age
			if(age >= 22){
				System.out.println("Ready for a wife. So happy.");
			}else{
				System.out.println("It's young. Wait..."); }}else if(sex == 'woman') {// Female, age
			if(age >= 20){
				System.out.println("You can go to your husband's house...");
			}else{
				System.out.println("Too young to marry..."); }}else{
			System.out.println("You can't get married if you don't know your gender."); }}}Copy the code

Running result:

Example: if the score is greater than 90 if the boy send a girlfriend, if the girl send a boyfriend

	// If the score is greater than 90 for boys and girls
		int score = 10;
		char c = 'male';
		if(score>90) {if(c=='male'){
				System.out.println("Send me a girlfriend.");
			}else{
				System.out.println("Send me a boyfriend."); }}Copy the code
2.1.5 Special if statements
		// Special form
		// You must require that there be only one statement in an if or ESle statement
			if(score>60)
				System.out.println("Good student");
			else
				System.out.println("Send me a girlfriend.");	
Copy the code

Computer practice: enter four seasons.

demand

Spring printout Spring blossoms

Summer summer nap

It’s autumn and the air is crisp

Winter hibernation

/ / 1
import java.util.Scanner;

class  Test
{
	public static void main(https://img.chengxuka.com/ruby0011/String[] args) 
	{

		// == Determine whether the contents of the basic data types are equal
		// Reference data type == To determine memory address
		// Equals equals ()

		Scanner sc = new Scanner(System.in);
		String str = sc.next();
		
	// Boolean falg= str.equals(" spring ");
      if(str.equals("Spring")){
   			System.out.println("Spring blossoms");
   		}else if(str.equals("Summer") ){
   			System.out.println("Summer nap");
   		}else if(str.equals("Autumn")){
   			System.out.println("Crisp autumn air");
   		}else if(str.equals("Winter")){
   			System.out.println("Hibernate in short sleeves."); }}}Copy the code

2.2 switch statement

2.2.1 Swtich Syntax rules
  1. The value of the expression expr must be one of the following:

Int, byte, char, short,enum; Java 7 after can be a String, cannot use Boolean, long, float, double, etc.

  1. The values in the case clause const must be constant values (img.chengxuka.com/ruby0011/ or f…
  2. Case statements are unordered.
  3. The default clause is optional (unnecessary)
  4. The break statement causes the program to jump out of the switch block after executing a case branch. Otherwise it will continue
2.2.2 Syntax Format
   switch(expression expr){case const1:
   			statement1;
   			break;
   		case const2:
   			statement2;
   			break; ... ...case constN:
  			statementN;
   			break;
   		default:
   			statement_dafault;
   			break;
   	} 
Copy the code
2.2.3 Execution process and Points for Attention:

Execution process:

Enter theswitchStatement, matching from top downcase. Match which one?caseWhich branch statement to execute. All of thecaseDo not meet the needs of the executiondefaultThe contents of thebreakHelp outswitchStatement, if not encountered during executionbreakContinue down until you encounterbreakSo far,Copy the code

Notes:

1. Switch is different from if: if applies to Boolean types. Switch is used on int, char, byte, short, enum, and String types. 2. The default statement is optional. 3. The value after case must be unique. 4. There is no order in the case. 5, Break, break, break, break Used to prevent switch penetration.Copy the code

Example code:

public class Demo26Switch {

	public static void main(String[] args) {
		/* * switch-case statement: select structure, multiple branches select one execution. Grammatical structure: * * * the switch/variable (expression) {/ / byte, short, int, char, enum, String * * case number 1: branch 1; Break; * * Case data 2: branch 2; Break; * * Case case 3: branch 3; Break; *... * default: the last branch; Break; *} * * /
		/* * Title: Recipes for the week, What to eat every day * Monday: Malatang * Tuesday: Braised pork in brown sauce * Wednesday: Hot and dry noodles * Thursday: Fried sauce noodles * Friday: Baked cold noodles * Saturday: Instant noodles * Sunday: Hot pot */
		
		int weekDay = 3;
		
		switch(weekDay){
		
		case 1:
			System.out.println("Malatang");
			break;
		case 2:
			System.out.println("Braised pork in brown sauce");
			break;
		case 3:
			System.out.println("Hot and dry noodles");
			break;
		case 4:
			System.out.println("Jajangmian");
			break;
		case 5:
			System.out.println("Baked cold noodles");
			break;
		case 6:
			System.out.println("Instant noodles");
			break;
		case 7:
			System.out.println("Hot pot");
			break;
		default:
			// Execute the default statement if none of the previous cases matches.
			System.out.println("Wrong information.");
			break;
		
		}
		
		System.out.println("over...."); }}Copy the code

Running result:

Exercise: Simply implement the switch statement

	   int i = 1;
	   switch(i){
   			case 1:
   				System.out.println("Big bear");
   				break;
   			case 2:
   				System.out.println("Bear");
          break;
   			case 3:
   				System.out.println("Strong bald head.");
   				break;
   			default:
   				System.out.println("Haaaa");
   				break;
   		}
Copy the code

Exercise: Judge spring, summer, fall and winter

Scanner sc = new Scanner(System.in);
		String str = sc.next();
		switch(str){
			case "Spring":
				System.out.println("Spring blossoms");
				break;
			case "Summer":
				System.out.println("Hot");
				break;
			case "Autumn":
				System.out.println("Crisp autumn air");
				break;
			case "Winter":
				System.out.println("Dripping water turns into ice.");
				break;
			default:
				System.out.println("Martian");
				break;
		}
Copy the code

Exercise: Requirement: Implement a calculator operation with switch

			Scanner  sc = new Scanner(System.in);
   		System.out.println("Enter the first operand :");
   		int a = sc.nextInt();
   		System.out.println("Please enter the operator");
   		String str = sc.next();
   		int b = 0;

   		// Use an if statement to help control that the second operand is not entered if it is ++ or --

   		if("+ +".equals(str)|| "--".equals(str)){
   		}else{
   			System.out.println("Please enter the second action :");
   			b = sc.nextInt();
   		}
   		switch(str){
   			case "+":
   				System.out.println(a+"+"+b+"="+(a+b));
   				break;
   			case "-":
   				System.out.println(a+"-"+b+"="+(a-b));
   				break;
   			case "*":
   				System.out.println(a+""+b+"="+(ab));
   				break;
   			case "/":
   				System.out.println(a+"/"+b+"="+(a/b));
   				break;
   			case "%":
   				System.out.println(a+"%"+b+"="+(a%b));
   				break;
   			case "+ +":
   				System.out.println("+ +"+a+"="+(++a));
   				break;
   			case "--":
   			     System.out.println("--"+a+"="+(--a));
   				break;
   			}
Copy the code
2.2.4 Special usage: case penetrating

Case penetration: The result of a missing or missing break statement in a case statement.

Step pit: Penetration of switch: After a case is successfully matched, the content after the case is executed and ends when a break is encountered. However, if there is no break statement, then the following cases no longer match and are executed directly. This phenomenon is called switch penetration.

Example code:

public class Demo27Switch {

	public static void main(String[] args) {
		/* * switch-case (); /* * switch-case (); * Switch applies to int, char, byte, short, enum, and String types. * * 2, default statement, is optional. * * 3, the value after the case must be unique. * * 4, the case is not in order. * * 5, Break, break, break, break Used to prevent switch penetration. * * Switch traversal: After a case is successfully matched, it executes the contents of the case and ends when a break is encountered. * If there is no break statement, then the following cases no longer match and are executed directly. This phenomenon is called switch penetration. * * /
		/* * Week 1, 3, 5: Instant noodles * Week 2, 4, 6: Porridge * Week 7: Don't eat */
		
		int weekday = 1;
		
		switch (weekday) {
		case 1:
		case 3:
		case 5:
			System.out.println("Instant noodles");
			break;
		case 2:
		case 4:
		case 6:
			System.out.println("Porridge");
			break;
		case 7:
			System.out.println("Do not eat");
			break;
		default:
			System.out.println("Wrong information.");
			break; }}}Copy the code

Running result:

Computer exercises:

// Requirements: Prints the number of days in the specified month

   		Scanner sc = new Scanner(System.in);

   		int month = sc.nextInt();

   		switch(month){

   			case 1:			

   			case 3:				

   			case 5:				

   			case 7:				

   			case 8:				

   			case 10:				

   			case 12:

   				System.out.println("31 days");

   				break;

   			case 2:

   				System.out.println(28 days /29 days);

   				break;

   			case 4:				

   			case 6:				

   			case 9:				

   			case 11:

   				System.out.println("30 days");

   				break;		

   		}

   		System.out.println("over!");

   	}
Copy the code