Java Flow Control

This chapter explores Java flow control statements. Mainly from the following aspects:

  • Java branch statements
  • Java loop statement

In Java, as in any other development language, branch statements and loop statements are essential, and with these two features we can accomplish something similar:

  1. Judge grade, excellent or good
  2. Perform operations related to the multiplication table

1. Branch statements

1.1 Introduction to Branch Statements

  • Branching statements selectively execute or skip specific statements based on certain conditions
  • In order to complete according to different conditions, get different results, to meet the needs of real life
  • There are several ways to implement branch statements in Java
    • 1)if: single branch statement. If it meets the requirement, enter the statement block
    • 2)if... else: Enter the if block if, else else block, or either
    • 3)if... else if... else if... else: multi-branch statement, enter a branch if both conditions are met, enter else if none is met
    • 4)switch... case: Implements the statement block

1.2 If single branch statement

If single branch statement, indicating that the statement block content will be entered as long as the condition is met, otherwise skip directly.

The left part of the figure represents the if single branch statement

/ / grammar
if(conditional expression){// If the condition is true, the statement is executed. Otherwise, skip the statement
}
Copy the code

Case study:

If the score is greater than or equal to 90, set the grade as excellent, otherwise ignore

public static void main(String[] args) {
    int score = 91;
    String grade = "";
    if(score>=90) {
        grade = "Good";
        System.out.println("Xiao Ming gets a drumstick.");
    }
    System.out.println("end...");
}
Copy the code

Note: Pay attention to testing in future code sessions. Otherwise conditions are particularly easy to miss

1.3 the if… Else double branch statement

if… Else is called a double branch, and if the condition is met it goes to the if block, otherwise else;

That is, the if or else block must go into one of the branches; There are also no two branches entering at the same time;

On the right, if… Else usage scenarios

Grammar:

// Format double branch statements if or else always enter a branch
if(conditions) {// If condition is true, enter
}else{
    // Otherwise enter else
}
Copy the code

Case study:

If Xiao Ming scores at least 90 points, he will be awarded a chicken leg, otherwise he can only eat vegetables

public static void main(String[] args) {
    int score = 89;
    // Note: Pay attention to testing in the future code process. Otherwise conditions are particularly easy to miss
    if(score>=90) {
        System.out.println("Xiao Ming gets a drumstick.");
    }else {
        System.out.println("Xiao Ming was ordered to eat only vegetables.");
    }
    System.out.println("end...");
}
Copy the code

1.4 the if… else if… The else syntax

if… else if… Else, also known as a multi-branch statement, can specify multiple conditions.

But only one can enter the branch

Grammar:

/ / grammar
if(conditions) {// meet the entry
}else if(conditions2) {// meet the entry
}else if(conditions3) {// meet the entry
}else{
   	//都不满足,进入else
}
Copy the code

Case study:

Different conditions enter different branches, for example: score 88, awarded a spicy chicken feet

public static void main(String[] args) {
    int score = 50;
    // Note: Pay attention to testing in the future code process. Otherwise conditions are particularly easy to miss
    if (score >= 90) {
        System.out.println("Xiao Ming gets a drumstick.");
    } else if (score >= 80) {
        System.out.println("A spicy chicken feet!");
    } else if (score >= 60) {
        System.out.println("Reward a dozen exercises!");
    } else {
        System.out.println("Xiao Ming was beaten up.");
    }
    System.out.println("end...");
}
Copy the code

Note: If more than one condition is met at the same time, it will be matched automatically from the top down. When you enter one branch, you don’t enter another branch.

1.5 the switch… A case statement

When dealing with multiple options, in addition to using if… Java also provides another branch statement, which is switch… case

The switch statement is executed from the case tag that matches the option value until the statement ends or the break keyword is encountered

Grammatical structure:

  • The return value of an expression in switch must be one of the following types:int. byte.char.short.The enumeration.string
  • The value in the case clause must beconstant, and the values in all case clauses should be different;
  • The default clause is the final execution
  • breakThe case statement is used to jump out of the switch block after executing a case branch.
// Give fixed content
switch(expression){caseconstant1:
        / / block
        break;
    caseconstant1:
        / / block
        break;
    caseconstant1:
        / / block
        break;
    default:
        // Statement block: similar to else
}
Copy the code

Case study:

Get different levels based on different values

public static void main(String[] args) {

    int top = 1;
    switch (top) {

        case 1:
            System.out.println("Congratulations to the overall champion!!");
            break;
        case 2:
            System.out.println("Congratulations to runner-up!!");
            break;
        case 3:
            System.out.println("Congratulations to the second runner-up!!");
            break;
        case 4:
            System.out.println("Congratulations number four!!");
            break;
        case 5:
            System.out.println("Congratulations number five!!");
            break;
        default:
            System.out.println("The bottom"); }}Copy the code

Note:

If the value of the expression is consistent with the content of the constant, it means that the code block is entered

Second, loop statements

2.1 Introduction to Loop Statements

To execute specific code repeatedly under specified conditions.

For example, add and sum between 1 and 100;

public static void main(String[] args) {
    int sum = 0;
    for (int i = 1; i <= 100; i++) {
        sum = sum+i;
    }
    System.out.println("sum=" + sum);
}
Copy the code

There are three basic loops provided in Java:

  • The for loop
    • 1) Plain for loop
    • 2) Enhance the for loop
  • while
  • do… while

2.2 a for loop

The for loop statement is a generic construct that supports iteration, using a counter or similar variable that is updated after each iteration to control the number of iterations

For is generally used to specify the number of cycles, which is more convenient

1. Cycle components:

A. initialization B. loop condition C. body, contents of the loop D. iteration (changing the original value)

/ / syntax:
forInitialization; Conditional judgment; Iteration) {// The loop body is the code that executes over and over again
}
Copy the code

2,case

Prints even columns between 1 and 100

for (int i = 1; i <= 100; i++) {
    if(i%2= =0){
        System.out.println("i="+ i); }}Copy the code

3, for execution order

  1. Step one, yesiInitialize it to 1
  2. Step two: JudgeiIs it less than 100?
  3. Step three, if returntrueTo execute the corresponding statement block content
  4. The fourth step, execute the statement block content, carry out iteration, williPerform the ++ operation
  5. The fifth step is to judge and execute after the iterationThe second stepoperation
  6. Step 6, proceed to the code block if satisfied, ifIf you don't, you jump out of the loop

2.3 the while loop

When the condition is true, the while loop executes a statement (which can also be a statement block). The general format is

Syntax: [initial value]while(Condition) {/ / block
    // iterate [change the initial value]
}
Copy the code

If the start condition is false, the body of the while loop is not executed once

Case study:

Add the sum between 1 and 100

public static void main(String[] args) {
    int result = 0;
    int i = 1;
    while (i <= 100) { // Determine the condition
        / / block
        result += i;
        System.out.println("i=" + i + " result="+ result); i++; }}Copy the code

2.4 the do… while

If you want the body of the loop to execute at least once, you should put the detection criteria last. This can be done using a do/while loop;

And while the do… The biggest difference between while is:

  • While: Judge first, then execute
  • do… While doing, then judging, so do… The while is executed at least once

Syntax format:

Syntax :(execute first, before deciding: execute at least once regardless of condition)do{
    / / block[iteration]}while(Judgment condition);Copy the code

Case study:

Add the sum between 1 and 100

public static void main(String[] args) {
    int result = 0;
    int i = 1;
    do {
        result += i;
        System.out.println("i=" + i + " result=" + result);
        i++;
    } while (i <= 100);
}
Copy the code

2.5 Interrupt the Loop

Java provides the continue and break keywords to terminate the loop and continue execution.

  • continueUsed to terminate the loop, thecontinueAnything after the keyword is not executed; However,continueIterates, and then executes the next loop;
  • breakUsed to jump out of the current loop, all content belonging to the loop will terminate execution;

The following are the precautions for the use of both:

  • Break can only be used in switch statements and loop statements.
  • Continue can only be used in circular statements.
  • The labeled statement must be immediately at the head of the loop. A labeled statement cannot precede a non-loop statement.
  • Statements after break and continue cannot be followed by other statements, because the program never executes statements after break and continue.

Case study:

When I =5, the result is obtained by using different keywords

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        //break; / / 1 2 3 4
        continue; //1 2 3 4 6 7 8 9 10
    }
    System.out.println("continue==>i = " + i);
}
Copy the code

2.6 Nested loops

public static void main(String[] args) {

    // 1. Outer layer: control the number of lines 1-9
    // 2. Inner layer: control the number of columns in each row (count multiple kills)
    for (int i = 1; i <= 9; i++) {
        // aa: label usage: split must be written at the head of the loop
        for (int j = 1; j <= i; j++) {
            System.out.print(j + "*" + i + "=" + (j * i) + "\t");
        }
        System.out.println(); / / a newline}}Copy the code

B

The first1Question: to achieve a query of the number of days of the month program keyboard input month to judge the number of days in this month. < leap year conditions: can be4Divisible and cannot be divided by100Divisible or divisible by400Aliquot > first2Tax =(salary - threshold point)* Tax rate Industry has1.The service sector2.manufacturing3.agricultural1.The tax threshold for the service industry is20002000Above yuan need to pay10% of personal income tax2.The tax threshold for manufacturing is3000yuan3000Above yuan need to pay5% of personal income tax3.The threshold for agricultural taxation is1500yuan1500Above yuan need to pay2% of individual income tax prompts users to choose industry, input salary, output after tax salary. Third problem: freight calculator: the transportation company calculates the freight to the user. The longer the journey, the lower the freight per kilometer. The basic freight per kilometer per ton of goods is P, the weight of goods is W, the distance is S, and the discount is D, so the calculation formula of the total freight f is f= P * W * S *(1-d)
       s<250There is no discount250<=s <500 2% discount500<=s<1000 5% discount1000<=s<2000  8% discount2000The above15% discount. The first day of January 1, XXXX is the day of the week.1900January 1, 2001 is Monday. Question 5: Complete the bank withdrawal procedure according to the flow chartCopy the code

6. Write a calendar program: input a month according to the format output calendar prompt for that month:1900January 1, 2003 is a MondayCopy the code

This blog post by IT Grasshopper elder brother original release! Welcome to reprint, indicate the source!