preface

C: In the last article we introduced the concept of process control statements. In this article we will begin to study the selection control statements. So what is the syntax for implementing select control statements in Java?

In this article, we’ll take a look at one of the most commonly used selection constructs: the if series selection constructs.

A series of reading

  • The Java syntax | control statements and flow chart”
  • The Java syntax | if choose structure”
  • The Java syntax | switch selection structure”

The base if selection structure

The basic if selection syntax is the most basic structure syntax in the if family of selection constructs. It is the simplest selection structure and can only be used for one branch of the process.

/ / grammar
// A condition is usually a judgment consisting of relational operators
// The result of the condition is a Boolean value, either true or false
if(Condition) {// Block of code to execute when the condition is true
}
Copy the code

Case requirement: If Peggy gets more than 90 points in Java, Teacher Cha will award her a OnePlus 8 Pro.

// Declare a variable to store Page's Java score
int score = 91;

// Apply the basic if syntax
if (score > 90) {
    System.out.println("Teacher Cha awarded a OnePlus 8 Pro.");
}

System.out.println("End of procedure!");
Copy the code

The teacher said: apply the grammar, using the relational operator, to achieve a very simple selection case, is not very easy.

The basis of complex conditions if

Now look at the conditions in the following case, it’s not so easy.

Case requirement: If George scores more than 90 in Java and 80 in music, or 100 in Java and 70 in music, Teacher Cha will award him a OnePlus 8 Pro.

Faced with this kind of scenario, it can not be realized by ordinary relational operators alone, but can be solved well by combining logical operators.

// Declare variables to store George's Java score and music score respectively
int jScore = 60;
int mScore = 81;

// Relational operators combine logical operators
// Considering the precedence of the operator, you can use () to increase the precedence of some expressions, which is also a way to increase readability under complex conditions
// The addition of () should become an instinct, which is a conditional reflex after learning mathematics in compulsory education
if ((jScore > 90 && mScore > 80) || (jScore == 100 && mScore > 70)) {
    System.out.println("Teacher Cha awarded a OnePlus 8 Pro.");
}

System.out.println("End of procedure!");
Copy the code

If-else selects the structure

When we hit the code at the top, if the conditions are not met, there seems to be no action. How is it possible that only the teacher rewards the student and no student is punished? Let’s look at another example.

Case requirement: SUSIE will be rewarded with a OnePlus 8 Pro if she scores more than 90 on the Java test, otherwise she will be punished by buying a OnePlus 8 Pro for Her.

For this case, we can still use the basic If syntax.

// The condition is true
if (score > 90) {
    System.out.println("Teacher Cha awarded a OnePlus 8 Pro.");
}

// The condition is not true
// if (score <= 90) {
    // system.out.println (" SUSIE cried and bought A OnePlus 8 Pro for Teacher Cha. Teacher Cha was very touched." );
// }

// You can write it like this
/ /! It means the opposite, which is the opposite of something
if(! (score >90)) {
    System.out.println("SUSIE cried and bought A OnePlus 8 Pro for Teacher Cha, who was very touched.");
}
Copy the code

But knowing that the two results are mutually exclusive, you have to write the judgment again, and the more complex the condition, the more difficult it is to write.

For example, if you want to write the if case based on the complex condition you just wrote.

// Declare variables to store George's Java score and music score respectively
int jScore = 60;
int mScore = 81;

/ / set up
if ((jScore > 90 && mScore > 80) 
    || (jScore == 100 && mScore > 70)) {
    System.out.println("Teacher Cha awarded a OnePlus 8 Pro.");
}

// Untenable case
if(! ((jScore >90 && mScore > 80) 
    || (jScore == 100 && mScore > 70))) {
    System.out.println("Reward George for buying A OnePlus 8 Pro for Teacher Cha.");
}

System.out.println("End of procedure!");
Copy the code

Headache, we can use if-else syntax to solve the condition of mutual exclusion easily. The if-else selection structure can handle simple mutually exclusive branching cases.

/ / grammar
if(Condition) {// Block 1
} else {
    // Block 2
}
Copy the code

Use if-else to solve the above case requirements.

// Declare a variable to store SUSIE's Java exam scores
int score = 90;
// Use if-else syntax
// if: if else: otherwise
if (score > 90) {
    System.out.println("Teacher Cha awarded an iPhone 11 Pro.");
} else {
    System.out.println("SUSIE cried and bought A OnePlus 8 Pro for Teacher Cha, who was very touched.");
}
Copy the code

Teacher Zha said: OnePlus 8 Pro (system.out.println (” XXX “);) OnePlus 8 Pro (system.out.println (” XXX “);) OnePlus 8 Pro (system.out.println (” XXX “)) .

Multiple if selection structures

We know the basic if to handle single-branch selection and if-else to handle mutually exclusive branches, but what if there are more than one branching case?

Case requirements: If Peppa scores 80 or above in Java exam, Teacher Zha will reward her with OnePlus 8 Pro; if Peppa scores 60 or above in Java exam, teacher Zha will reward her with OnePlus Ear; otherwise, she will be punished to buy An iPhone 11 Pro for Teacher Zha.

Faced with this requirement, if-else can only handle mutually exclusive branches and therefore cannot be used, so the solution using the base if is as follows.

// Declare a variable to store Page's Java exam scores
int score = 90;

if (score >= 80) {
    System.out.println("Teacher Cha awarded her a OnePlus 8 Pro.");
}

// If you don't add && to the limit, then Paige will get >80 and Miss Cha will go bankrupt
if (score >= 60 && score < 80) {
    System.out.println("Teacher Cha awarded her a Yijia Yuner.");
}

if (score < 60) {
    System.out.println("Paige cried and bought An iPhone 11 Pro for Zha, who was very touched.");
}
Copy the code

There is no doubt that the base IF still needs to add more than one condition, but for scope-type judgments, if the scope is not well controlled, then the subsequent if conditions will be redundant because each base IF is independent. Java provides a simplified solution to this problem: the multiple IF selection structure.

Multiple if selection structure: can handle the condition branching case of segmentation, it is a top-down selection judgment, as long as one condition is satisfied, the rest of the condition no longer perform the judgment. Therefore, do not arbitrarily arrange the conditions, and put the conditions that are easy to satisfy at the bottom, otherwise, after the conditions that are easy to satisfy are judged to be true, the subsequent other conditions will not be judged.

/ / grammar
if(conditions1) {
    // Block 1
} else if(conditions2) { // There can be multiple else if
    // Block 2
} else { // Can be omitted
    // Block 3
}
Copy the code

// Store test scores
int score = 90;

// use if-else if-else statements
/ * * note: * 1. Else if must cooperate if use, if can only write one, else if you can write a lot of a * 2. The structure of the if, else if the judgement is top-down choice, as long as one of the conditions of above, no longer perform * 3 at the bottom of the other conditions. You can use this in combination with else, which executes the else block content */ when all the above conditions fail
if (score >= 80) {
    System.out.println("Teacher Cha awarded her a OnePlus 8 Pro.");
} else if (score >= 60) { // There is no need to restrict the < 80 condition, because as long as >=80, no further judgment is made
    System.out.println("Teacher Cha awarded her a Yijia Yuner.");
} else {
    System.out.println("Paige cried and bought An iPhone 11 Pro for Zha, who was very touched.");
}
Copy the code

Nested if selection structure

Students living in Beijing, Shanghai, Guangzhou and Shenzhen are impressed by the subway stations in the morning and evening rush hours, right? Before taking the subway, we need to have two checks, the first is the security check and the second is the ticket check. Train stations are similar.

In the face of such multiple checks, its logic is not multiple If judgments executed sequentially from top to bottom, but only after passing the first judgment can we enter the second judgment. Facing this scenario, we can use the If statement more flexibly.

Nested if scenarios: Add additional judgments if the previous conditions are met. It can enhance the flexibility of programs through the cooperation of outer and inner statements. In Teacher Zha’s opinion, when the business scene is clearly described, fu Zhi will naturally write out the corresponding code.

if(conditions1) {
    if(conditions2) 
        // Block 1
    } else {
        // Block 2}}else {
    // Block 3
}
Copy the code

Case requirements: The school holds a sports meeting, and the students who run within 10 seconds in the 100-meter race are qualified to enter the final, and then enter the men’s or women’s group according to their gender

// Declare a variable to store 100 meters
int score = 9;
// Declare a variable to store gender
String gender = "Female";

// use nested if statements
// Note: There will be no division if you do not qualify for the finals
if (score < 10) { // Can make it to the finals
    System.out.println("In the finals!");
    if ("Male".equals(gender)) { // Assign groups
        System.out.println("In the men's division!");
    } else {
        System.out.println("In the girls' division!"); }}Copy the code

String comparison

In most cases, we use the == relational operator when comparing content, but not when we encounter special types.

Instead of using ==, compare strings using equals().

String is a reference datatype, which is a bit special. Use the equals method to compare the contents of strings.

// the == sign can be used to compare the values of the basic data types.
int num1 = 10;
int num2 = 10;
// System.out.println(num1 == num2); // true

char gender1 = 'male';
char gender2 = 'male';
// System.out.println(gender1 == gender2); // true

// ------------------

// If it's a string, don't use the == sign to compare, use equals() instead
// Because strings refer to data types, the == sign is actually comparing the address value of the data rather than the content of the comparison
// So == is likely to cause problems with your string content comparison because it compares address values
// Even if you find two strings equal to true with ==, that's where the constant pool concept comes in.
// Remember not to compare strings with ==! You'll see why in the later object oriented phase.
String str1 = "I am a string";
String str2 = "I am a string";
System.out.println(str1.equals(str2));
Copy the code

Check the teacher set questions

Just look at the fake handle, let’s practice a few, practice.

To simulate the login

Program with if: Get username and password from keyboard, if username and password are correct, then “Welcome to the world of XXX!” “Or” Wrong username or password! .

Tip: you can pre-set a fake username and password.

The man-machine mora

Input the boxing from the console, 1 on behalf of rock, 2 on behalf of scissors, 3 on behalf of cloth, the computer randomly punch, compare the outcome, complete this code function.


Random number generation

Random number is often used in the program, we can use it to simulate a lot of business, the following introduction to a Java generation of random number of gameplay.

Math.random() can randomly generate decimals between [0.0,1.0)
// [0.0,1.0) represents an interval, equivalent to 0.0 <= num1 < 1.0
// Left closed and right open include the data on the left and exclude the data on the right
// [0.0,1.0] also represents an interval, equivalent to 0.0 <= num1 <= 1.0
// Left close right close is to include the left side of the data, also include the right side of the data
// If you want to know more about the interval, go to Baidu for the relevant math knowledge
double num1 = Math.random();

/* * Based on the above method, if you want to specify the generation of a certain range of random numbers, you can derive a formula. * random number formula :(int)(math.random () * (max-min)) + min; * /
// case 1: generate random integers between [0,10)
// [0.0,1.0) * 10 --> [0,10)
int num2 = (int)(Math.random() * 10);

// case 2: generate random integers between [5,14]
int num3 = (int)(Math.random() * 9) + 5;

// example 3: if you want to generate a random integer between [6,20], you can interpret it as [6,21], and then you can repeat the formula above
int num4 = (int)(Math.random() * 15) + 6;
Copy the code

Lucky draw

Lucky draw: Enter a 4-digit member number. If the hundred digit of the member number is equal to the random number generated, then the member is a lucky member and will be rewarded with an iPhone 11 Pro! Prompt for reasonable results.

Tip: Get a 4-digit, individual digit example:

int num = 1234;
/ / one thousand
int qian = num / 1000;

/ / one hundred
int bai = num / 100 % 10;

/ / 10
int shi = num / 10 % 10;

/ / bits
int ge = num % 10 % 10;
Copy the code

Afterword.

The use of choice structures is not usually a problem for you. Because it is very close to our daily life, it is very readable. Of course, if you still can’t understand, don’t forget the flow chart!

Teacher Zha said: For the learning of technology, teacher Zha has always followed the following steps: With a simple demo to let it run first, and then learn it the most commonly used API and configuration can let yourself up, finally, on the basis of proficiency in the spare time reading the source to try to make myself to be able to see clearly its running mechanism, part of the cause of the problem, at the same time, draw lessons from these technology to enhance your own code level.

So in the teacher’s article, the early basic are small white, only interspersed with a very small amount of source research. Of course, such as the small white update, you still like, the late will not regularly dedicated to part of the technology of the source code analysis.