Collect it quickly! You don’t know the process control knowledge in Java. Why do you raise your salary?

Time:2021-8-7

Java process control

  • Basic stage Directory:
  1. User interaction scanner
  2. Sequential structure
  3. Select structure
  4. Cyclic structure
  5. break & continue
  6. Exercises

1. Scanner object

  • The basic syntax we learned before did not realize the interaction between programs and people, but Java provides us with such a tool class that we can obtain user input. Java. Util. Scanner is a new feature of Java 5. We can get user input through the scanner class.
  • Basic syntax:
Scanner s = new Scanner(System.in);
  • Get the input string through the next() and nextline() methods of the scanner class. Before reading, we generally need to use hasnext() and hasnextline() to judge whether there is still input data.
  • next():
  1. Be sure to read valid characters before you can end the input// Must be input, otherwise the program will not stop
  2. The next () method will automatically remove the whitespace encountered before entering valid characters// Hello world only outputs hello because there are spaces
  3. Only when a valid character is entered, the space entered after it will be used as a separator or terminator. / ‘/ End only if there is a space in the program ‘
  4. Next() cannot get a string with spaces.

Examples of using next():

package com.company.base;

import java.util.Scanner;

public class demo1 {

    public static void main(String[] args) {

        //Create a scanner object to accept keyboard data
        Scanner scanner = new Scanner(System.in);

        System. Out. Println ("receive in next mode:");

        //Judge whether the user has entered a string
        if (scanner.hasNext()){
            //Receive in next mode
            String str = scanner.next();
            System. Out. Println ("output content is:" + STR ");
        }
        scanner.close(); // When you run out of IO streams, remember to turn off the occupied memory. IO streams are the input and output streams that exchange information with the computer
    }
}
  • nextLine()

    1. Take enter as the ending character, that is, the nextline () method returns all characters before entering carriage return.
    2. You can get blank.
package com.company.base;

import java.util.Scanner;

public class demo2 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println ("please enter data");

        if(scanner.hasNextLine()){
            String abc = scanner.nextLine();
            System. Out. Println ("output:" + ABC);
        }
        scanner.close();
    }
}
  • Scanner for judging integers and decimals
package com.company.base;

import java.util.Scanner;

public class demo4 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);


        //Receive data from keyboard
        int i = 0;
        float f = 0.0f;

        System. Out. Println ("please enter an integer:");


        //If... So...
        if (scanner.hasNextInt()){
            i = scanner.nextInt();
            System. Out. Println ("integer data:" + I);
        }else {
            System. Out. Println ("input is not integer data");
        }
        System.out.println ("please enter decimal");
    if (scanner.hasNextFloat()){
        f = scanner.nextFloat();
        System. Out. Println ("decimal data:" + F);
    }else {
        System. Out. Println ("input is not decimal data!");
    }
scanner.close();

    }
}

Make a simple calculator

package com.company.base;

import java.util.Scanner;

public class demo5 {


    public static void main(String[] args) {
        //We can enter multiple numbers and find their sum and average. Press enter to confirm each number. Enter a non number to end the input and output the execution result:
        Scanner scanner = new Scanner(System.in);




        //And
        double sum = 0;
        //Calculate how many numbers are entered
        int m = 0;

        //Judge whether there is any input through circulation, and sum and count each time in it
        while (scanner.hasNextDouble()){

            double x = scanner.nextDouble();

            m = m+1;//m++

            sum = sum + x;

            System. Out. Println ("you input the" + m + "th data, then count the money, and the result is sum" + sum ");
        }

        System. Out. Println (the sum of M + numbers is "+ sum);
        System. Out. Println (M + "the average value of the number is" + (sum / M));


        scanner.close();
    }
}

2. Sequential structure

  • The basic structure of Java is sequential structure. Unless otherwise specified, it is responsible for executing sentence by sentence in order.
  • Sequential structure is the simplest algorithm structure.
  • Between statements and between boxes, it is carried out in the order from top to bottom. It is composed of several processing steps executed in turn. It is a basic algorithm structure that any algorithm is inseparable from.

    If you haven’t figured it out, give it to the following run and you’ll know

package com.company.base;

public class demo6 {
    public static void main(String[] args) {
        System.out.println("1");
        System.out.println("2");
        System.out.println("3");
        System.out.println("4");
        System.out.println("5");
        System.out.println("6");
        System.out.println("7");
        System.out.println("8");
    }
}

3. Select structure (very important)

  • If single selection structure
  • If double selection structure
  • If multiple selection structure
  • Nested if structure
  • Switch multiple selection structure
  1. If single selection structure
  • We often need to judge whether something is feasible before we execute it. Such a process is represented by an IF statement in the program
  • Syntax:
If (Boolean expression){
    //If the Boolean expression is true, the statement that will be executed, otherwise skip
}
  1. If double selection structure
  • When two judgments are required, a double choice structure is required, so there is an if else structure.
  • Syntax:
If (Boolean expression){
    //If the Boolean expression has a value of true
}else{
    //If the value of the Boolean expression is false
}
package com.company.ifdemo;

import java.util.Scanner;

public class if2 {


    public static void main(String[] args) {
    //If the test score is greater than 60, you will pass, and if it is less than 60, you will fail
        Scanner scanner = new Scanner(System.in);

        System. Out. Println ("please enter grade:");

        int score = scanner.nextInt();

        if (score>60){
            System.out.println ("pass");
        }else {
            System.out.println ("fail");
        }
    }
}
  1. If multiple selection structure
  • We found that the code just now does not conform to the actual situation. In the real situation, there may be ABCD and interval multi-level judgment. For example, 90-100 is a, 80-90 is B, and so on. Many times in life, we have more than just these two choices, so we need a multi-choice structure to deal with such problems.
If (Boolean expression 1){
    //If the value of Boolean expression 1 is true, execute the code
}Else if (Boolean expression 2){
    //If the value of Boolean expression 2 is true, execute the code
}Else if (Boolean expression 3){
    //If the value of Boolean expression 3 is true, execute the code
}else{
    //If none of the above Boolean expressions is true, execute the code
}
package com.company.ifdemo;

import java.util.Scanner;

public class if3 {


    public static void main(String[] args) {
        //If the test score is greater than 60, you will pass, and if it is less than 60, you will fail
        Scanner scanner = new Scanner(System.in);

        System. Out. Println ("please enter grade:");

        int score = scanner.nextInt();
/*
An IF statement can have at most one else statement, which follows all else if statements.
An IF statement can have several else if statements, which must precede the else statement.
Once one else if statement is detected as true, the other else if and else statements will skip execution
 */
        if (score == 100) {
            System. Out. Println ("Congratulations, you got full marks");
        } else if (score < 100 && score >= 90) {
            System.out.println ("class a");
        } else if (score < 90 && score >=80) {
            System.out.println ("level B");
        } else if (score < 80 && score >= 70) {
            System.out.println ("level C");
        }else if (score<70 && score>=60){
            System.out.println ("level D");
    }else if (score<60 && score>=0){
            System. Out. Println ("if you fail, study hard");
        }
  }
}
4. Nested if structure

    *It is legal to use nested if... Else statements. That is, you can use an if or else if statement in another if or else if statement. You can nest else if... Else like an IF statement.

    *Grammar
If (Boolean expression 1){
    //If the value of Boolean expression 1 is true, execute the code
    If (Boolean expression 2){
        //If the value of Boolean expression 2 is true, execute the code
    }
}

4. Switch multi selection structure

  • Another implementation of the multiple selection structure is the switch case statement.
  • The switch case statement can judge whether a variable is equal to a value in a series of values. Each value is called a branch.
  • The variable types in the switch statement can be:

    • Byte, short, int, or char
    • Starting with Java se 7
    • Switch supports string type
    • At the same time, the case tag must be a string constant or literal.
Switch(expression){
            case value:
                //Statement
                break;// Optional
            case value:
                //Statement
                break;// Optional
            //You can have any number of case statements
        Default: // optional
            //Statement
        }

First example:

package com.company.jiaohuan;

public class JH {
    public static void main(String[] args) {
       //
        char grade = 'A';

        switch (grade){
            case 'A':
                System.out.println ("excellent");
                break;// Optional
            case  'B':
                    System.out.println ("good");
                break;// Optional
            case 'C':
                System.out.println ("pass");
                break;// Optional
            case  'D':
                System. Out. Println ("keep going");
                break;// Optional
            case 'E':
                System. Out. Println ("pull brother");
                break;// Optional
            default:
                System.out.println ("unknown level");
        }
    }
}

Second example:

package com.company.jiaohuan;


public class JH2 {
    public static void main(String[] args) {
        String name = "chb";
//JDK 7 new feature, the expression result can be a string!!!
        //The essence of characters is still numbers!!!

        //Decompile Java -- class (bytecode file) -- decompile (idea)
switch (name){
    case "RAP":
        System.out.println("RAP");
        break;
    Case "whole activity":
        System.out.println ("whole live");
    default:
        System. Out. Println ("you have a sister");
}
    }
}

5. Circulation structure

  • while Loop
While (Boolean expression){
    //Cyclic content
}
*As long as the Boolean expression is true, the loop will continue to execute.
*In most cases, we will stop the loop. We need a way to invalidate the expression to end the loop.
*In a few cases, the loop needs to be executed all the time, such as the server's request response listening, etc.
*If the loop condition is always true, it will cause infinite loop [dead loop]. We should try to avoid dead loop in normal business programming. It will affect the program performance or cause the program to jam and crash!
package com.company.whiledemo01;

public class Whiledemo1 {
    public static void main(String[] args) {

        //Output 1-100

        int i = 0;

        while (i < 5201314){

            i++;
            System.out.println(i);
        }
    }
}

Calculate 1 + 2 ++ one hundred

public class Whiledemo3{
    public static void main(String[] args) {
        //Calculate 1 + 2 ++ one hundred

        int i = 0;
        int sum = 0;
        while (i<=100){
            sum = sum + i;
            i++;
        }
        System.out.println(sum);
    }
}
  • Do… While loop

    • For the while statement, if the condition is not met, it cannot enter the loop. But sometimes we need to perform at least once even if the conditions are not met.
  • The do… While loop is similar to the while loop, except that the do… While loop is executed at least once
do{
    //Code statement
}While (Boolean expression);
  • Use the do… While statement to calculate 1 + 2 ++ one hundred
package com.company.whiledemo01;

public class dowhiledemo1 {
    public static void main(String[] args) {
        int i = 0 ;
        int sum = 0 ;
        do{
            sum = sum + i;
            i++;
        }while ((i<=100));
        System.out.println(sum);
    }
}

public class dowhiledemo2{
    public static void main(String[] args) {

        int a = 0;
        while (a<0){
            System.out.println(a);
            a++;
        }
        System.out.println("===========");
        do{
            System.out.println(a);
            a++;
        }while (a<0);
    }
  • The difference between while and do… While:
  • While is to judge before execution, while dowile is to judge after execution!

    • Do… While always ensures that the loop is executed at least once! This is their main difference.
  • For loop
  • An enhanced for loop is introduced in Java 5, which is mainly used for arrays

Recommended Today

Uniapp is pushed by the server and cannot be received offline. Detection steps: PHP on the server

1. Check whether the parameters are correct.2. Do not use transparent transmission mode first.3. Is the manufacturer channel message content set4. Setting to open a specific page in the application is the intent parameter.5. Whether the intent parameter is correctintent:#Intent; Component = package name / io.dcloud.pandoraentry; S.UP-OL-SU=true; S. Title = “. URLEncode”; S. Content = […]