Java process control of Java se

User interaction scanner

Basic knowledge of Scanner

definition

The Scanner scanner can scan the data entered by the user on the console through the Scanner class

Basic grammar

Scanner sc = new Scanner(System.in);

Scanner gets the string entered by the console

Method 1: next() method

example
package com.lan.scanner;

import java.util.Scanner;//When using this class, you need to import the package

public class Demo01 {
    public static void main(String[] args) {
        //User interaction scanner
        Scanner scanner = new Scanner(System.in);
        System.out.println("use next Method reception:");

        if(scanner.hasNext()) {
            //Here the program waits for user input
            String str = scanner.next();//When the string entered on the console is hello world
            System.out.println("The string you entered is:"+str);//The string you entered is: hello
        }

        //All IO stream classes should be closed after use to save resources. If they are not closed, they will always occupy resources
        scanner.close();
    }
}

summary
  1. The hasNext() method is usually used to determine whether the console has input
  2. The next() method filters out white space characters that are encountered before valid characters are entered
  3. Only when a valid character is read, the following white space character is considered a separator or terminator
  4. next() cannot get a string with spaces

Method 2: nextLine() method

example
package com.lan.scanner;

import java.util.Scanner;

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

        System.out.println("use nextLine Reception mode:");

        //Determine whether there is string input
        if(scanner.hasNextLine()) {
            String str = scanner.nextLine();//When the string entered on the console is hello world
            System.out.println("The string you entered is:"+str);//The string you entered is: hello world
        }

        //To develop good habits, remember to turn off resources
        scanner.close();
    }
}

summary
  1. The hasNextLine() method is usually used to determine whether the console has input
  2. Using the Enter key as the terminator, you can get a string with spaces

Scanner gets other types of console data

In addition to obtaining strings, Scanner also has corresponding methods and has methods to obtain other types of data and judge whether the console has data input. The following takes int and float data as examples, and the format is basically consistent with the string.

for example
package com.lan.scanner;

import java.util.Scanner;

public class Demo03 {
    public static void main(String[] args) {
        //Get shaping data through Scanner
        Scanner scanner = new Scanner(System.in);

        //Prompts the user for integer data
        System.out.println("Please enter an integer data:");
        if (scanner.hasNextInt()) {//Judge whether the user enters data
            int i = scanner.nextInt();//Define a variable to receive data
            System.out.println("The integer data you entered is:"+i);
        } else {
            System.out.println("The data you entered is not an integer!");
        }

        //Prompt the user for decimal data
        System.out.println("Please enter a decimal number:");
        if (scanner.hasNextFloat()) {//Judge whether the user inputs data. This judgment can sometimes be omitted and is often used in the loop
            float f = scanner.nextFloat();//Define a variable to receive data
            System.out.println("The decimal data you entered is:"+f);
        } else {
            System.out.println("The data you entered is not decimal!");
        }

        scanner.close();
    }
}

Sequential structure

The most basic structure of Java is sequential structure. Unless otherwise specified, it is executed from top to bottom.

Sequential structure is the simplest algorithm structure.

Sequential structure is the most basic algorithm structure that no code block can leave.

Select structure

Basic syntax of if single choice structure

if(Boolean expression) {
    //The code executed when the condition is true, that is, the value of the Boolean expression is true
}

example

package com.lan.structure;

import java.util.Scanner;

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

        System.out.println("Please enter what you want to enter");
        String str = scanner.nextLine();

        if (str.equals("hello")) {
            System.out.println("What you entered is hello");
        }

        System.out.println("ending");

        scanner.close();
    }
}

Basic syntax of if double choice structure

if(Boolean expression) {
    //The code executed when the condition is true, that is, the value of the Boolean expression is true
} else {
    //The code executed when the condition is false, that is, the value of the Boolean expression is false
}

example

package com.lan.structure;

import java.util.Scanner;

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

        System.out.println("Please enter your grade:");
        double score = scanner.nextDouble();

        if (score >= 60) {
            System.out.println("Congratulations on your achievement!");
        } else {
            System.out.println("I'm sorry your grades are not up to standard!");
        }

        scanner.close();
    }
}

if multiple choice structure basic syntax

if(Boolean expression 1) {
    //If the value of Boolean expression 1 is true, the code executed
} else if(Boolean expression 2) {
    //If the value of Boolean expression 2 is true, the code executed
} else if(Boolean expression 3) {
    //If the value of Boolean expression 3 is true, the code executed
} else {
    //The code to be executed when the value of the above Boolean expression is false
}

example

package com.lan.structure;

import java.util.Scanner;

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

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

        double score = scanner.nextDouble();

        if (score == 100) {
            System.out.println("Congratulations, full marks");
        }else if (score>=90 && score<100) {
            System.out.println("A level");
        }else if (score>=80 && score<90) {
            System.out.println("B level");
        }else if (score>=70 && score<80) {
            System.out.println("C level");
        }else if (score>=60 && score<70) {
            System.out.println("D level");
        }else if (score<60 && score>=0) {
            System.out.println("I'm sorry I failed");
        }else {
            System.out.println("The score you entered does not meet the requirements");
        }

        scanner.close();
    }
}

Nested if statements

if(Boolean expression 1) {
    //If the value of Boolean expression 1 is true, the code executed
    if(Boolean expression 2) {
        //If the value of Boolean expression 2 is true, the code executed
    }
}

example

package com.lan.structure;

import java.util.Random;
import java.util.Scanner;

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

        Random r = new Random();

        //Guess the number, a random number between 1 and 10
        int num = r.nextInt(10);//Generate random number
        int guess = num+1;

        System.out.println("Please enter the number you guessed");

        int i = scanner.nextInt();

        if (i==guess) {
            System.out.println("Congratulations, you guessed right");
        } else {
            if (guess>i) {
                System.out.println("Guess it's small");
            } else {
                System.out.println("Guess big");
            }
        }

        //Output computer generated random numbers
        System.out.println(guess);

        scanner.close();
    }
}

switch multiple selection structure

switch(expression) {
        //If the break is not written, case penetration will occur
    case value:
        //sentence
        break;//Optional
    case value:
        //sentence
        break;//Optional
    //There can be any number of case statements
    default://Optional
        //sentence
}

The variable type in the switch statement can be

byte, short, int, char

Starting with Java se 7, string types are also supported

Also, the case tag must be a string constant or literal

Example 1

package com.lan.structure;

public class SwitchDemo01 {
    public static void main(String[] args) {
        char c = 'A';

        //Without break, case penetration will occur
        switch (c) {
            case 'A':
                System.out.println("A");
                break;
            case 'B':
                System.out.println("B");
                break;
            case 'C':
                System.out.println("C");
                break;
            default:
                System.out.println("D");
        }
    }
}

Example 2

package com.lan.structure;

public class SwitchDemo02 {
    public static void main(String[] args) {
        String s = "lan";
        switch (s) {
            case "lan":
                System.out.println("lan");
                break;
            case "man":
                System.out.println("man");
                break;
            default:
                System.out.println("wu");
        }
    }
}

Cyclic structure

while Loop

grammar

while(Cyclic conditions) {
    //Code executed when conditions are met
}

//Avoid dead loops and have statements that stop the loop
//If the conditions of the loop are not met, the loop will not be entered at all, that is, the code that meets the conditions will not be executed

example

package com.lan.structure;

public class WhileDemo01 {
    public static void main(String[] args) {
        //Calculate the sum of 1-100
        int i = 1;
        int sum = 0;
        while (i<=100) {
            sum += i;
            i++;
        }
        System.out.println("1-100 The sum of is:" + sum);
    }
}

do... while loop

grammar

do {
    //Code statement
} while(Cyclic conditions);
    
//do... The while loop is similar to the while loop, except that do While executes the code in the do code block first, and then determines whether the loop condition is met, that is, do While will loop at least once
//while is to judge first and then cycle, do while is to cycle first and then judge

example

package com.lan.structure;

public class DoWhileDemo01 {
    public static void main(String[] args) {
        //Calculate the sum of 1-100
        int i = 1;
        int sum = 0;

        do {
            sum += i;
            i++;
        } while (i<=100);
        System.out.println("1-100 The sum of is:"+sum);
    }
}

for loop

grammar

for(initialization;Cyclic conditions;to update) {
    //Code that the loop condition is satisfied
}

//Dead cycle
for(;;) {
    //code
}

Example 1: calculate the odd sum and even sum of 1-100

package com.lan.structure;

//Calculate the odd and even sums of 1-100
public class ForDemo01 {
    public static void main(String[] args) {
        
        int evenSum = 0;
        int oddSum = 0;

        for (int i = 1;i<=100;i++) {
            if (i%2==0) {
                evenSum += i;
            } else {
                oddSum += i;
            }
        }
        System.out.println("Even sum:"+ evenSum);
        System.out.println("Odd sum:"+ oddSum);
    }
}

Example 2: use the while loop or for loop to output the number that can be divided by 5 in 1-1000, and output every three lines

package com.lan.structure;

//Use the while loop or for loop to output the number that can be divided by 5 in 1-1000, and output every three lines
public class ForDemo02 {
    public static void main(String[] args) {
        //Loop with while
        int i = 1;
        int count = 0;
        while (i<=1000){
            if (i%5==0) {
                System.out.print(i + " ");//Yes + "\ t"
                count++;
                if (count==3) {//It is also possible to judge directly with i
                    System.out.println();
                    count = 0;
                }
            }
            i++;
        }
        System.out.println();
        System.out.println("**********************");

        //Loop with for
        int count1 = 0;
        for (int j = 1;j<=1000;j++) {
            if (j%5==0) {
                System.out.print(j+" ");
                count1++;
                if (count1==3) {
                    System.out.println();
                    count1 = 0;
                }
            }
        }

        System.out.println();
        System.out.println("**********************");
        //Improvement of the above algorithm
        int count2 = 0;
        for (int k=1;k<=1000/5;k++) {
            System.out.print(k*5 + " ");
            count2++;
            if (count2==3) {
                System.out.println();
                count2=0;
            }
        }
    }
}

Example 3: print 99 multiplication table

package com.lan.structure;

//Print 99 multiplication table
public class ForDemo03 {
    public static void main(String[] args) {
        for (int i = 1;i<=9;i++) {
            for (int j = 1;j<=i;j++){
                System.out.print(j + "*" + i + "=" + i*j + "  ");
            }
            System.out.println();
        }
    }
}

Add for loop

Let's learn about it first, and then learn more when we wait for the array

Enhanced for loops were introduced after Java 5

grammar

for(Declaration statement:expression) {
    //Loop execution code
}
//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 array element at this time
//Expression: an expression is the name of the array to be accessed, or a method whose return value is an array

break and continue

Definitions and differences

break: it can be used in the loop structure to forcibly exit the loop and no longer execute the statements in the loop, that is, no longer judge whether the loop conditions are met. break is also used in the switch selection structure.

continue: used in the loop statement body to terminate a loop, that is, skip the rest of the code in the loop body, and then judge the next loop.

Label label (understand)

Often used in nested loops.

give an example

package com.lan.structure;

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

Keywords: Java JavaSE

Added by knetcozd on Fri, 24 Dec 2021 18:42:41 +0200