Outline of this paper:

Why process control

Usually we do a thing, generally there will be a fixed process.

For example, if you want an apple, you need to find the fridge, open the fridge door, take out the apple, return to the couch, and start eating.

You can’t get the apple before you open the fridge. Sequential control. It’s a process.

If you want a banana, you’ll find the process is similar, just take the banana out of the fridge.

Along the way, you’ll discover what you end up eating, depending on your choices. You’re going to eat apples, you’re going to get apples from the fridge, you’re going to eat bananas, you’re going to get bananas from the fridge. Control by choice, this is also a process.

There’s a situation where one banana isn’t enough for you, you want a few more, until you don’t want any, and then you repeat the process, and when you’re full, you stop. This repeated execution of control, terminated by a condition, is also a process.

The computer is the electronic expression of the real world, so in the computer world, the program operation needs such flow control.

Whether it’s machine language, assembly language, or high-level programming language, this concept is involved in determining the path that your code will take and how the computer interacts with the user.

What does flow control look like in the Java language?

Input and output

We program to solve some real problem, like writing an addition program, to get the sum of two numbers.

One of the most important features of a program, as you’ll see, is that it takes input, it processes it, and it outputs the result.

So how does Java accept input?

Scanner is introduced

Java provides the Scanner utility class, which you can use to retrieve user input. The basic syntax is as follows:

// Build a Scanner object with the standard input stream
Scanner scanner = new Scanner(System.in);

// Reads the input line and gets the string
String nextLineStr = scanner.nextLine();

// When reading an input string, the Spaces around the string are ignored, because the Spaces act as delimiters or terminators
String nextStr = scanner.next();

// InputMismatchException (InputMismatchException)
int nextInt = scanner.nextInt();

Copy the code

System.in is a standard input stream that can be used to receive keyboard input or data from other specified data sources.

Scanner is a simple text Scanner that can parse primitive types and strings. New Scanner(system.in) builds a Scanner object, scanner.nextline () reads an input line and gets a string, and scanner.next() can also get a string, but not strings with Spaces on either side. Scanner.nextint () reads an integer as input, and any other basic type of int works as well.

The Scanner USES

We can look at the sample code:

package cn.java4u.flowcontrol;

import java.util.Scanner;

/** * Enter demo **@authorThe snail *@fromPublic number: snail Internet */
public class InputDemo {

    public static void main(String[] args) {

        // Build a Scanner object with the standard input stream
        Scanner scanner = new Scanner(System.in);

        // Reads the input line and gets the string
        String nextLineStr = scanner.nextLine();

        // When reading an input string, the Spaces around the string are ignored, because the Spaces act as delimiters or terminators
        String nextStr = scanner.next();

        // InputMismatchException (InputMismatchException)
        int nextInt = scanner.nextInt();

        System.out.println("-- The following is the printed value --");
        System.out.println("nextLineStr:" + nextLineStr);
        System.out.println("nextStr:" + nextStr);
        System.out.println("nextInt:"+ nextInt); }}Copy the code

You will notice that there is an import java.util.scanner in the sample code; Scanner is a class in the Java library, so you need to import the syntax to use it.

The sample code has three console inputs. Let’s enter the following data to see the output:

I am snail snail 666 8Copy the code

The string entered on the first line is followed by Spaces, and the string entered on the second line is preceded by Spaces. The output is as follows:

NextStr: snail 666 nextInt:8Copy the code

You’ll notice that the whitespace after nextLineStr is still there, and the whitespace before and after nextStr is gone.

Let’s look at another type of input:

I am snail snail 666 7Copy the code

When we type two lines and press Enter, the program directly prints the result:

NextLineStr: I'm a snail nextStr: snail 666 nextInt:7Copy the code

This shows the difference between nextLine() and next(). NextInt () is a conversion based on next() and can be considered the same as next().

The starting character The separator The characteristics of
nextLine() Any character A carriage return (Enter) You can get a string with a space
next() Non-whitespace character The blank space Cannot get a string with a space

The output

In the previous code, we printed the contents to the console as system.out.println ().

System.out is the standard output stream, which can be used not only to display output, but also to write to a specified output destination, such as a file.

Println is short for print line. If the output does not want to wrap, print() can be used. In addition, Java supports formatting output with printf() for easy reading.

Here is the sample code:

package cn.java4u.flowcontrol;

/** * output demo *@authorThe snail *@fromPublic number: snail Internet */
public class OutputDemo {

    public static void main(String[] args) {

        // Print and wrap
        System.out.println("-- Start demo --");
        // Output does not wrap
        System.out.print("Print without newline [");
        System.out.print("1");
        System.out.print("2");
        System.out.print("3");
        System.out.print("]");
        / / only a newline
        System.out.println();
        // Format output
        double d = 66600000.8888;
        // Result if no formatting is performed: 6.66000008888E7
        System.out.println("Result without formatting:" + d);
        System.out.printf("Default format: %f", d);
        System.out.printf("; No decimal format: %.0f", d);
        System.out.printf("; One decimal bit format: %.1f", d);
        System.out.printf("; Two digit decimal format: %.2f", d); }}Copy the code

The following output is displayed:

6.66000008888E7 Default formatting: 66600000.888800; Format without decimal: 66600001; One-digit decimal format: 66600000.9; Two - digit decimal format: 66600000.89Copy the code

%f is a placeholder for Java’s floating-point formatting function. By default, floating-point is formatted as a 6-digit decimal output, but you can also specify decimal output by following the example.

In addition to floating point numbers, Java formatting provides a variety of placeholders to format various data types into specified strings. The following are common placeholders:

A placeholder instructions
%d Formatted output integer
%x Format output hexadecimal integer
%f Format output floating point number
%e Format output scientific notation for floating-point numbers
%s Formatted string

Note that since % represents a placeholder, two consecutive %% % represents a % character itself.

Three process control structures

Now that we know how input and output are represented in the Java world, let’s take a look at the flow controls involved in program processing.

Sequential structure

The basic flow structure of a program is a sequential structure, and so is Java. If not specified, the program is executed line by line in order.

Choose structure

But a lot of times, we need to decide if something works before we implement a piece of logic. For an addition program, for example, we have to require that the values involved in the operation be numbers, not strings.

Such flow control can be achieved by selecting the structure.

If single select structure

If you want the logic to remain the same before and after a particular condition is processed, you can use the if single-select structure.

The syntax is as follows:

If (Boolean expression){// Statement executed when Boolean expression result is true}Copy the code

Here is sample code for printing the maximum value of two integers:

package cn.java4u.flowcontrol;

import java.util.Scanner;

/** * if single select structure **@authorThe snail *@fromPublic number: snail Internet */
public class IfSingleChoiceDemo {

    public static void main(String[] args) {

        // Build a Scanner object with the standard input stream
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter the integer a:");
        int a = scanner.nextInt();

        System.out.println("Please enter the integer b:");
        int b = scanner.nextInt();

        // Initialize the maximum value of a
        int max = a;

        // if b is larger than a, assign b to Max
        if (a < b) {
            max = b;
        }
        System.out.println("max:"+ max); }}Copy the code

We initialize the variable Max with the number a, and only assign the value of b to Max if b is found to be greater than a. So when a is equal to 10 and b is equal to 9, the logic in the if curly braces can’t go anywhere, and when a is equal to 10 and b is equal to 11, the logic in the if curly braces can’t go anywhere.

If double selection structure

Sometimes we have a condition where there are two different logics, so we can use the if double selection structure.

The syntax is as follows:

If (Boolean expression){// statement executed when Boolean expression result is true}else{// statement executed when Boolean expression result is false}Copy the code

Here is sample code for printing the absolute value of an integer:

package cn.java4u.flowcontrol;

import java.util.Scanner;

/** * if double select structure **@authorThe snail *@fromPublic number: snail Internet */
public class IfDoubleChoiceDemo {
    public static void main(String[] args) {

        // Build a Scanner object with the standard input stream
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter the integer a:");
        / / 10-10
        int a = scanner.nextInt();

        // Initialize the absolute value variable
        int abs;

        if (a < 0) {
            abs = -a;
        } else {
            abs = a;
        }
        System.out.println("abs:"+ abs); }}Copy the code

We use abs to initialize the absolute value variable. For the integer a to be evaluated, when its value is 10 or -10, it will follow different branches of if to perform different logic.

If multiple selection structure

When we have more than one condition, we can perform logic in more than two cases, so we can use the if multiple selection structure.

The syntax is as follows:

If (Boolean expression 1){// Boolean expression 1 executed when true}else if(Boolean expression 2){// Boolean expression 2 executed when true}else {// Boolean expression 1 executed when false}Copy the code

Here is a sample code for a good or bad 100-point rating:

package cn.java4u.flowcontrol; import java.util.Scanner; /** ** if multiple options ** @author snail * @from Public class IfMultiChoiceDemo {public static void main(String[] args) {// Use the standard input stream to build a Scanner object Scanner scanner = new Scanner(System.in); System.out.println(" Please enter your grade (percent) :"); Int score = scanner. NextInt (); int score = scanner. NextInt (); If (score > 0 && score < 60) {system.out.println ("不 完 "); } else if (score >= 60 && score < 80) {system.out.println (" good "); } else if (score >= 80 && score < 90) {system.out.println (" good "); } else if (score >= 90 && score <= 100) {system.out.println (" excellent "); } else {system.out.println (" invalid input "); }}}Copy the code

The program of evaluation of good and bad grades has interval multi-level judgment, which is more suitable for if multi-choice structure.

If nested selection structure

We can use the if nested selection structure when we encounter conditions that can be separated from multiple conditions and have different execution logic. The if nested selection structure can be considered as a variant of the if multi-selection structure.

The syntax is as follows:

If (Boolean expression 1){// If (Boolean expression 2){// If (Boolean expression 2)}}Copy the code

The following is a sample code after the distortion of the 100-point grade rating:

package cn.java4u.flowcontrol;

import java.util.Scanner;

/** * if nested selection structure **@authorThe snail *@fromPublic number: snail Internet */
public class IfNestChoiceDemo {
    public static void main(String[] args) {

        // Build a Scanner object with the standard input stream
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter your grade (percentage) :");

        / / 58,68,88,96,120 switching
        int score = scanner.nextInt();

        if (score >= 0 && score <= 100) {

            if (score < 60) {
                System.out.println("Unqualified");
            } else if (score < 80) {
                System.out.println("Qualified");
            } else if (score < 90) {
                System.out.println("Good");
            } else {
                System.out.println("Good"); }}else {
            System.out.println("Illegal importation"); }}}Copy the code

Different from ordinary if multi-selection structure code, if nested selection makes two layers of selection, the first layer is the validity of the input, the second layer is to do grades.

Switch selection structure

We sometimes have limited conditions, and it’s a matter of determining whether a variable is equal to a value in a series, and then hitting different values leads to different logic. At this point, you can use switch to select the structure.

The syntax is as follows:

Switch (var){case Value1: // var Execute statement break when value1 hits; Case value2: // var Statement break executed when value2 is hit; // There can be any number of case statements // the default request will go to this branch if none of the above cases hit or break will go to this branch}Copy the code

If we package the programs mentioned above for the user, we can provide a unified gateway through the Switch, directing the user to type 1 to route to the maximum program, type 2 to route to the absolute value program, and type 3 to route to the good and bad grades program. Example code is as follows:

package cn.java4u.flowcontrol;

import java.util.Scanner;

/** * switch select structure **@authorThe snail *@fromPublic number: snail Internet */
public class IfSwitchChoiceDemo {
    public static void main(String[] args) {

        // Build a Scanner object with the standard input stream
        Scanner scanner = new Scanner(System.in);

        System.out.println(Please select the program you want to run (type 1 for maximum, 2 for absolute value, and 3 for good or bad score):);

        int choice = scanner.nextInt();

        switch (choice) {
            case 1:
                System.out.println("-- Start finding the maximum of two numbers --");
                IfSingleChoiceDemo.main(null);
                break;
            case 2:
                System.out.println("-- start taking the absolute value --");
                IfDoubleChoiceDemo.main(null);
                break;
            case 3:
                System.out.println("-- Good or bad grades at the beginning --");
                IfMultiChoiceDemo.main(null);
                break;
            default:
                System.out.println("Illegal importation"); }}}Copy the code

Run the program and type 1. You’ll see that the Max subroutine starts executing and the program ends when the Max prints, indicating that break is working as the current branch blocker. If the break code is hit, case 2, Case 3, and default will not be hit.

Not every case needs a break. When two cases have the same logic, you can ignore the break and merge them. For example, when typing 4, I want the same effect as 3.

case 3:
case 4:
    System.out.println("-- Good or bad grades at the beginning --");
    IfMultiChoiceDemo.main(null);
    break;

Copy the code

Case logic without a break penetrates to the next case, using the code logic of the next case.

Note that the switch selection structure is a variant of the if multi-selection structure for special scenarios. JavaSE 8 supports the types of variables byte, short, int, char, String, and ENUM.

Loop structure

Programs sometimes run a piece of logic over and over again, and if the code is organized in a sequential structure plus a selection structure, you need to write a lot of repetitive code. Let’s say I want the sum from 1 to 5:

1 + 2 + 3 + 4 + 5 =?Copy the code

My code might look like this:

package cn.java4u.flowcontrol;

/** * while loop structure demonstrates **@authorThe snail *@fromPublic number: snail Internet */
public class WhileCircleDemo {

    public static void main(String[] args) {

        int a = 1;
        int sum = 0;

        System.out.println("The current value of a is :" + a);
        // a is added to sum
        sum = sum + a;
        // A itself plus one
        a = a + 1;

        System.out.println("The current value of a is :" + a);
        sum = sum + a;
        a = a + 1;

        System.out.println("The current value of a is :" + a);
        sum = sum + a;
        a = a + 1;

        System.out.println("The current value of a is :" + a);
        sum = sum + a;
        a = a + 1;

        System.out.println("The current value of a is :" + a);
        sum = sum + a;
        
        System.out.println("sum:"+ sum); }}Copy the code

You’ll notice that there’s a lot of repetition, and at a = 5, the summation ends and the output comes out. It would be much easier to write code if there was a mechanism to express this repetitive logic in a concise way.

This mechanism is a circular structure.

While loop structure

The most common loop structure is the while loop, which has the following syntax:

While (Boolean expression){// loop content}Copy the code
  • As long as the Boolean expression is true, the loop continues.

  • We will stop the loop most of the time, so we need a way to stop the loop by making the Boolean expression false.

  • In a few cases, the loop is always executed, such as the server’s request response listening.

  • If the loop condition is always true, it will cause an infinite loop. This should be avoided as it will cause the program to freeze and crash.

Use while to express the sum as follows:

// Initialize the value
a = 1;
sum = 0;

while (a <= 5) {
    // a is added to sum
    sum += a;
    // A itself plus one
    a++;
}
System.out.println("while sum:" + sum);

Copy the code

Do while loop structure

If you look at the while statement, you can’t enter the loop until the condition is met. But sometimes we need to do it at least once, even if the conditions are not met. Use the do while loop as follows:

do{
 // Loop content}where(Boolean expression)Copy the code
  • Unlike the “judge before execute” approach of a while loop, the “do while” loop is executed before judge.

  • The contents of the loop in do while are executed at least once.

The summation code for do while is as follows:

// Initialize the value
a = 1;
sum = 0;

do {
    // a is added to sum
    sum += a;
    // A itself plus one
    a++;
} while (a <= 5);
System.out.println("do while sum:" + sum);

Copy the code

For loop structure

In the summation code, we’ll see that a, like a counter, initializes a value with a = 1, and then we add a value to each loop as the number that we add to the sum, a <= 5 as the counter loop condition, determines whether we add up to 5 or 100, if we change it to a <= 100, If you add up to 100, you don’t do the loop anymore.

This is really a generic structure for iterative processing: initial values, termination conditions, and counters. So Java provides a for loop structure to simplify the while loop in this scenario, with the syntax:

for(Counter initialization; Boolean expression; Update counter after loop){// Loop content
}

Copy the code

The summation code for for is as follows:

sum = 0;
for (a = 1; a <= 5; a++) {
    sum += a;
}
System.out.println("for sum:" + sum);
Copy the code

For each loop structure

Sometimes, when we get a bunch of numbers, we don’t really care about their order, as long as we can walk through them. Let’s say I have a bunch of values in an array, and I don’t care about the index of the values, I just want to know what the sum of the values is. We can use the for each loop to iterate over a group of numbers. The syntax is as follows:

forElement type Element variable: array or iterator){// Loop content
}

Copy the code
  • For each is a simplification of the for special case where the object is an array or iterator object.

  • In contrast to the for loop structure, the for each loop structure does not reflect the initialization and updating of counters, and therefore does not specify the order of traversal, nor does it get an array or iterator index.

The summation code for each is as follows:

int[] array = {1.2.3.4.5};
sum = 0;
for (int temp : array) {
    sum += temp;
}
System.out.println("for each sum:" + sum);

Copy the code

The interruption of the loop structure

Loop structures always have a Boolean expression as a loop detection condition. If the Boolean expression is false, the loop is terminated, which is one way to break the loop.

In addition, Java provides two other ways to loop structured interrupts.

One is break. The syntax is as follows:

Loop structure {// Break before the code if(break Boolean expression){break; } // interrupt code}Copy the code
  • When a break Boolean expression returns true, it hits break and exits the entire loop structure. After the break, the code is no longer executed.

Example summation code is as follows:

int a = 1;
int sum = 0;
while (a <= 5) {

    // a is interrupted when a is 3
    if (a == 3) {
        break;
    }

    // a is added to sum
    sum += a;
    // A itself plus one
    a++;
}
System.out.println("while sum:" + sum);

Copy the code
  • I’m actually summation of 1 and 2, because I’m out of the loop when A is 3.

Note: If the loop structure is nested, break will exit only the current loop structure, not the outer loop structure.

The other is continue, with the following syntax:

Loop structure {// Pre-interrupt code if(interrupt Boolean expression){continue; } // interrupt code}Copy the code
  • When the interrupt Boolean expression returns true, the continue is hit, and the loop structure is interrupted when the next call is made. After the interrupt, the code will not be executed again and the loop structure will be called again.

Example code is as follows:

int i = 0;
while (i <= 5) {
    i++;
    // I is interrupted when I is 3
    if (i == 3) {
        System.out.println("Hit the continue");
        continue;
    }
    System.out.println("i=" + i);
}

Copy the code

Output:

I =1 I =2 Hit continue I =4 I =5 I =6Copy the code

The continue logic is hit when I is 3, and the next loop does not proceed, but enters the next one.

In simple terms, break breaks out of the current layer loop, the loop structure terminates, and continue breaks out when the next loop is called, and terminates when the next loop is called. Both are used in conjunction with if.

summary

This paper introduces the concept of flow control from real cases, which is mapped to the programming field. We abstract the execution of a program into an input-process-output process. It then introduces the implementation of input and output in the Java world, and then explains the three commonly used flow control structures in the process of processing: sequence structure, selection structure and loop structure, and lists the demo code. Readers can imitate the case practice, I believe you will have a more profound impression. Thank you for reading and sharing, welcome to comment and like!


I am snail, dachang programmer, focus on original technology and personal growth, is on the Internet. Welcome to pay attention to me, and the snail grow up together, we cattle ~ next see!