Java process control

Java process control

Scanner object

We use the Scanner class to get the user's input

Basic syntax: Scanner s=new Scanner(System.in);

Get the input string through the next() and nextLine() methods of Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to judge whether there is still input data

Scanner object

next():

  1. Be sure to read valid characters before you can end the input
  2. The next () method will automatically remove the blank space encountered before entering valid characters
  3. Only after a valid character is entered, the blank space entered after it will be used as a delimiter or terminator
  4. next() cannot get a string with spaces
package Javal technological process;

import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {
        //Create a scanner object to accept keyboard data
        Scanner scanner = new Scanner(System.in);//alt + ENTER
        System.out.println("use next Method receiving:  ");

        //Judge whether the user has entered a string
        if(scanner.hasNext())
        {
            String str=scanner.next();
            System.out.println("The input content is:"+str);
        }
        //If the class using IO stream is not closed, it will always occupy all resources. Form a good habit and close it after use
        scanner.close();

    }
}

nextLine()

  1. With enter as the terminator, that is, the nextLine() method returns all characters before the input carriage return
  2. Can get blank
package Javal technological process;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("use nextline Acceptance method:  ");

        if(scanner.hasNextLine())
        {
            String str=scanner.nextLine();
            System.out.println("The data entered is"+str);
        }
        scanner.close();
    }
}

Case 1

package Javal technological process.Scanner Use of;

import java.util.Scanner;

public class Demo03 {
    public static void main(String[] args) {
        System.out.println("Please enter an integer:");
        Scanner scanner = new Scanner(System.in);
        //Accept data from keyboard
        int i=0;
        float f=0.1f;

        if(scanner.hasNextInt())
        {
            i=scanner.nextInt();
            System.out.println("Integer data"+i);
        }
        else
        {
            System.out.println("The input is not integer data");
        }

        System.out.println("Please enter a decimal:");
        Scanner scanner1 = new Scanner(System.in);

        if(scanner1.hasNextFloat())
        {
            f=scanner1.nextFloat();
            System.out.println("Decimal data"+f);
        }
        else
        {
            System.out.println("The input is not decimal data");
        }

        scanner.close();
        scanner1.close();
    }
}

Case 2

package Javal technological process.Scanner Use of;

import java.util.Scanner;

public class Demo04 {
    public static void main(String[] args) {
        //We need to input multiple numbers and find the sum and average of them. Each number is determined by entering. The input is ended by non numbers and the execution result is output
        Scanner scanner = new Scanner(System.in);

        //and
        double sum=0;
        //Calculate how many numbers are entered
        int m=0;
        System.out.println("Please enter data:");
        //Through the loop to determine whether there is still input, and sum each time
        while(scanner.hasNextDouble()) {
            double x = scanner.nextDouble();
            //m++;
            m = m + 1;
            sum = sum + x;
        }
        System.out.println("The sum of the current number is"+sum);
        System.out.println("The average of the current number is"+sum/m);
    }
}

Sequential structure

The basic structure of JAVA is sequential structure. Unless otherwise specified, it will be executed sentence by sentence in order

Sequential structure is the simplest algorithm structure

Between statements and between boxes, it is carried out from top to bottom. It is composed of several steps executed in turn. It is the basic algorithm structure that every algorithm is inseparable from

package Javal technological process.struct;

public class ShuXuDome {
    public static void main(String[] args) {
        //Sequential structure
        System.out.println("hello1");
        System.out.println("hello2");
        System.out.println("hello3");
        System.out.println("hello4");
        System.out.println("hello5");
        System.out.println("hello6");
    }
}

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG trokdlbj-1645695851537) (C: \ users \ tangz \ appdata \ roaming \ typora user images \ image-20220224134726810. PNG)]

Select structure

if single selection structure

If (Boolean expression)

{/ / statement to be executed if Boolean expression is true

}

package Javal technological process.struct;

import java.util.Scanner;

public class ifDemo01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the content");
        String str=scanner.nextLine();

        //equals: compare strings for consistency
        if(str.equals("hello"))
        {
            System.out.println(str);
        }
        System.out.println("end");

        scanner.close();
    }
}

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-xjiwhb16-1645695851539) (C: \ users \ tangz \ appdata \ roaming \ typora user images \ image-20220224135442184. PNG)]

if double selection structure

Syntax:

If (Boolean expression)

{/ / if Boolean expression is true}

else

{/ / Boolean expression is false}

package Javal technological process.struct;

import java.util.Scanner;

public class IfDemo02 {
    public static void main(String[] args) {
        System.out.println("Please enter the test score");
        Scanner scanner = new Scanner(System.in);
        //If the test score is more than 60, you will pass, and if the test score is less than 60, you will fail
        double i=scanner.nextDouble();
        if(i>=60)
        {
            System.out.println("pass an examination");
        }
        else
        {
            System.out.println("Fail in the exam");
        }
        scanner.close();
    }
}

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG nshjghyu-1645695851539) (C: \ users \ tangz \ appdata \ roaming \ typora \ typora user images \ image-202202241402322202. PNG)]

if multiple selection structure

Syntax:

If (Boolean expression 1)

{/ / execute code if Boolean expression 1 is true}

Else if (Boolean expression 2)

{/ / if Boolean expression 2 holds, execute the code}

Else if (Boolean expression 3)

{/ / if Boolean expression 3 is true, execute the code}

else

{/ / if none of the above is true, execute the code}

package Javal technological process.struct;

import java.util.Scanner;

public class IfDemo03 {
    public static void main(String[] args) {
        System.out.println("Please enter the student's grade:");
        Scanner scanner = new Scanner(System.in);
        double score=scanner.nextDouble();
        System.out.println("Then the student's grade is:");
        if(score==100)
        {
            System.out.println("excellent");
        }
        else if(score<100&&score>=90)
        {
            System.out.println("A");
        }
        else if(score<90&&score>=80)
        {
            System.out.println("B");
        }
        else if(score<80&&score>=70)
        {
            System.out.println("C");
        }
        else
        {
            System.out.println("D");
        }
    }
}

An IF statement can have at most one else statement. The else statement is after the if else. An IF statement can have several else if statements. They must be before the else. Once one else if statement is checked to be true, other else if and else statements will skip execution

switch selection structure

Another implementation method of multi selection structure is switch case statement

The switch case statement determines that a variable is equal to a value in a series of values, and each value is called a branch

The switch statement variable type can be

byte,short ,int ,char,String

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

default: / / optional

//Statement

}

package Javal technological process.struct;

public class SwitchDemo01 {
    public static void main(String[] args) {
        //
        char grade='C';
        switch (grade)
        {
            case 'A':
                System.out.println("excellent");
                break;
            case 'B':
                System.out.println("good");
                break;
            case 'C':
                System.out.println("pass");
                break;
            case 'D':
                System.out.println("make persistent efforts");
                break;
            case 'E':
                System.out.println("fail");
                break;
            default:
                System.out.println("Unknown level");
                break;
        }
        //switch is the matching value. If there is no break after the case, there will be case penetration, that is, execute down in turn
    }
}

package Javal technological process.struct;

public class SwitchDemo02 {
    public static void main(String[] args) {
        String name="Mad God";
        //The expression after JDK7 can also be a string
        //String or number
        
        //Decompile Java -- class (bytecode file) -- decompile (IDEA)
        
        switch (name)
        {
            case "Qing Jiang":
                System.out.println("qingjiang");
                break;
            case "Mad God":
                
                System.out.println("Mad God");
                break;
            default:
                System.out.println(" ");
                break;
        }
    }
}

In bytecode mode: ctrl+shift+alt+s, find the copy path, find the file, find and open the java file from idea, and put the class file in it

Cyclic structure

while Loop

while is the most basic loop. Its structure is:

while (Boolean expression){

//Cyclic content

}

The loop continues as long as the Boolean expression is true

Most of us will stop the loop. We need an expression invalidation to end it

A small part of the loop needs to be executed all the time, such as the server listening for a response

package Javal technological process.XunHuan;

public class WhileDemo01 {
    public static void main(String[] args) {
        //Output 1-100
        int i=0;
        while(i<100)
        {
            i++;
            System.out.println(i);
        }
    }
}

Do while

For a while loop, if the conditions are not met, the loop cannot be entered, and do while occurs at least once

do{

//Code statement

}While (Boolean expression)

The difference between while and do while

While judges recycling first, do while executes recycling first

package Javal technological process.XunHuan;

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

The difference between do while and while

package Javal technological process.XunHuan;

public class DoWhileDemo02 {
    public static void main(String[] args) {
        int a=0;
        while(a<0)
        {
            System.out.println(a);
        }
        System.out.println("===================================================");
        do{
            System.out.println(a);
        }while(a<0);//Password input is generally do while
    }
}

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kebepjod-1645695851539) (C: \ users \ tangz \ appdata \ roaming \ typora user images \ image-20220224152629635. PNG)]

for loop

The for loop statement is a general structure that supports iteration and is the most effective. The most flexible cycle structure

The number of cycles is determined at the beginning of the for loop

For (initialization; Boolean expression; update){

//Code statement

}

package Javal technological process.XunHuan;

public class ForDemo01 {
    public static void main(String[] args) {
       int sum=0;
       //Initialize / / condition judgment / / iteration
        for(int a=1;a<=100;a++){
            sum=sum+a;
        }
        System.out.println(sum);
    }
}

package Javal technological process.XunHuan;
//Three numbers are required for one line. println is output line feed, and print is output line feed
public class ForDemo02 {
    public static void main(String[] args) {
        int a=1;
        while(a<=1000)
        {
            if(a%5==0)
            {
                System.out.println(a);
            }
            a++;
        }

        System.out.println("=====================================");
        for (int i = 1; i <= 1000; i++) {
            if(i%5==0)
            {
                System.out.println(i);
            }
             if(i%(5*3)==0)
            {
                System.out.print("\n");
            }
        }
    }
}

package Javal technological process.XunHuan;

public class ForDemo03 {
    public static void main(String[] args) {
        for(int i=1;i<=9;i++)
        {
            for(int a=1;a<=i;a++)
                System.out.print(a+"*"+i+"="+(i*a)+"\t");
            System.out.println();
        }

    }
}

[the external chain image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-o8qdtbbo-1645695851540) (C: \ users \ tangz \ appdata \ roaming \ typora user images \ image-20220224155608416. PNG)]

Enhanced for statement

java5 refers to an enhanced for loop that is primarily used for arrays or collections

The syntax format of Java enhanced loop for loop is as follows:

For (declaration statement: expression)

{

//Code sentence

}

Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the circular statement block, and its value is equal to the value of the array element at this time

Expression: the expression is the name of the array to be accessed, or the method whose return value is array

package Javal technological process.XunHuan;

public class ForDemo04 {
    public static void main(String[] args) {
        int[] numbers={10,20,30,40,50};//Defines an array

        for (int i = 0; i < 5; i++) {
            System.out.println(numbers[i]);
        }
        System.out.println("==================================================");
        //The element of the variable array, which assigns the number in the numbers array to x
        for(int x:numbers){
            System.out.println(x);
        }
    }
}

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-jcwcafm1-1645695851540) (C: \ users \ tangz \ appdata \ roaming \ typora \ typora user images \ image-20220224170431746. PNG)]

break continue

Break in the main part of any loop statement, you can use break to control the flow of the loop. Break is used to forcibly exit the loop without executing the remaining statements in the loop. (break statements are also used in switch statements)

The continue statement is used in a loop statement to terminate a loop process, that is, to skip the statement that has not been executed in the loop body, followed by the determination of the next loop

package Javal technological process.XunHuan;

public class BreakDemo {
    public static void main(String[] args) {
        int i=0;
        while(i<100)
        {
            i++;
            if(i==30)
                break;
        }
        System.out.println(i);
    }
}

package Javal technological process.XunHuan;

public class ContinueDemo {
    public static void main(String[] args) {
        int i=0;
        while(i<100){
            i++;
            if(i%10==0)
               {System.out.println(i);
                continue;}
            System.out.print(i+"\t");
        }
    }
}

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-2ysm6ovu-1645695851540) (C: \ users \ tangz \ appdata \ roaming \ typora \ typora user images \ image-20220224171651763. PNG)]

About goto keyword

This can be achieved through a labeled break or continue

"Label" refers to the identifier followed by a colon, for example: label;

For Java, the only place where the label is used is before the loop statement, and the only reason for using the label before the loop statement is that we want to nest another loop in it. Because the break and continue keywords usually only interrupt the current loop, but if they are used with the label, it will interrupt to the place of the label

package Javal technological process.XunHuan;

public class LabelDemo {
    public static void main(String[] args) {
        //Print all prime numbers between 101-150
        int count=0;
         outer:for (int i=101;i<150;i++)
        {
            for(int j=2;j<i/2;j++)
            { if(i%j==0)
                    continue outer;}
            System.out.println(i+"\t");
        }

    }
}

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-uko6gdqi-1645695851541) (C: \ users \ tangz \ appdata \ roaming \ typora user images \ image-202202241738150. PNG)]

Text01

Print a triangle

package Javal technological process.XunHuan;

public class TextDome01 {
    public static void main(String[] args) {
        //Print five lines of triangles
        for (int i = 1; i <=5; i++) {
            for(int j=4;j>=i;j--)
            { System.out.print(" ");}
            for(int j=1;j<=i;j++)
            {
                System.out.print("-");
            }
            for(int j=1;j<=i-1;j++)
            {
                System.out.print("-");
            }
            System.out.println();
        }
    }
}

[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-uiafs0zj-1645695851541) (C: \ users \ tangz \ appdata \ roaming \ typora user images \ image-20220224174321317. PNG)]

Keywords: Java Back-end

Added by Jeyush on Thu, 24 Feb 2022 11:56:16 +0200