Java process control

Posted by unstable_geek on Mon, 24 Jan 2022 23:29:33 +0100

Java process control

1 user interaction Scanner

Scanner class to get user input

Scanner s = new Scanner(system.in);

There are also * next() and nextLine() methods in the class to obtain the input string. Before reading, we need to use hasNext() and hasNextLine() * to judge whether there is any input data.

//Create a scanner object to receive keyboard data
Scanner scanner = new Scanner(System.in);
System.out.println("use next Reception mode:");

//Judge whether the user has entered a string
if(scanner.hasNext()){
    //Receive in next mode
    String str = scanner.next();
    System.out.println("The output contents are:"+str);
}

System.out.println("use next Reception mode:");
//Judge whether the user still has input
if (scanner.hasNextLine()){
    //Receive using nextLine
    String str = scanner.nextLine();
    System.out.println("The output contents are:"+str);
}

//All classes belonging to the IO stream will always occupy resources if they are not closed. Make a good habit of closing them when they are used up
scanner.close();

  • next()

    1. You must read valid characters before you can end the input;
    2. The next() method will automatically remove the blanks encountered before entering valid characters (Hello World - > Hello);
    3. Only after a valid character is entered, the blank space entered after it will be used as a separator or terminator;
    4. next() cannot get a string with spaces.
  • nextLine()

    1. End with Enter, that is, the nextLine() method returns all characters before entering carriage return;

    2. Can get blank.

      //Common usage
      Scanner scanner = new Scanner(System.in);
      System.out.println("Please enter data:");
      String str = scanner.nextLine();
      System.out.println("The output contents are:"+str);
      scanner.close();
      

Minority Scanner class methods: hasNextInt(), hasNextFolat()······

public static void main(String[] args){  //psvm
    //Enter multiple numbers and calculate their sum and average value. 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;
    //Count the number of times to enter a number
    int con = 0;
    //Judge whether there is any input through circulation, and sum and count each time in it
    while(scanner.hasNextDouble()){
        double x = scanner.nextDouble();
        con = con + 1; //con++
        sum = sum + x;
        System.out.println("You entered the number"+con+"Data, current result sum="+sum);//soup
    }
    
    System.out.println(con + "The sum of the numbers is:"+sum);
    System.out.println(con + "The average number is:"+(sum/con));
    
    scanner.close();
}

2 sequential structure

The simplest algorithm structure, statements are executed from top to bottom.

It is a basic algorithm structure that any algorithm is inseparable from!

3 select structure

1) if single choice structure

//grammar
if(Boolean expression){
    //The statement that will be executed if the Boolean expression is true
}

2) if double selection structure

//grammar
if(Boolean expression){
    //The statement that will be executed if the Boolean expression is true
}else {
    //The statement that will be executed if the Boolean expression is false
}

3) if multiple selection structure

//grammar
if(Boolean expression 1){
    //The statement that will be executed if the value of Boolean expression 1 is true
}else if(Boolean expression 2){
    //The statement that will be executed if the value of Boolean expression 2 is true
}else if(Boolean expression 3){
    //The statement that will be executed if the value of Boolean expression 3 is true
}else {
    //Statement executed if none of the above Boolean expressions is true
}

4) Nested if structure

//grammar
if(Boolean expression 1){
    //Statement to execute if Boolean expression 1 is true
    if(Boolean expression 2){
        //Statement to execute if Boolean expression 2 is true
    }
}

5) switch multi selection section structure

switch case statement

Judge whether a variable is equal to a value in a series of values, and each value becomes a branch.

switch(expression){
    case value:
        //Execute statement
        break;//Optional (if not written, penetration will occur)
    case value:
        //Execute statement
        break;//Optional
    //There can be any number of case statements
    default://Optional
        //Execute statement
}
  • The variable types in the switch statement can be:
    • byte, short, int, or char
    • Starting from Java SE7, support String type – > decompile implementation, Java - > class - > idea (hash value, the essence of characters is numbers)
    • The case tag must be a string constant or literal

4 cycle structure

1) while loop

//grammar
while(Boolean expression){
    //Internal circulation
}
//Calculate 1 + 2 + ··· + 100 =?
int i = 0;
int sum = 0;
while(i<=100){
    sum = sum + i;
    i++;
}
System.out.println(sum);
  • 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 get stuck and run away!

2) 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{
    //Execute statement
}while(Boolean expression);
//Calculate 1 + 2 + ··· + 100 =?
int i = 0;
int sum = 0;
do{
    sum = sum + i;
    i++;
}while(i<=100);
System.out.println(sum);
  • Difference between While and do While:
    • While judge first and then execute; Do while is to execute first and then judge!
    • Do... while is to ensure that the loop is executed at least once! This is their main difference.

3) for loop

Although all loop structures can be represented by while or do... While, Java provides another statement - for loop, which makes some loop structures simpler.
for loop statement is a general structure that supports iteration. It is the most effective and flexible loop structure.

//grammar
for(initialization;Boolean expression;to update){
    //Execute statement
}
//example
for(int i=1;i<=100;i++){
    System.out.println(i);
}
System.out.println("for End of cycle!");
//Dead cycle
for(;;){
    
}

//Exercise 1: calculate the odd sum and even sum between 0-100
int oddSum = 0;
int evenSum = 0;
for(int i=0;i<=100;i++){  //Shortcut key input 100 for
    if(i%2!=0){ //Odd number
        oddSum+=i; //oddSum = oddSum + i;
    }else { //even numbers
        evenSum+=i;
    }
}
System.out.println("Odd sum:"+oddSum);
System.out.println("Even sum:"+evenSum);

//Exercise 2: use the while or for loop to give the number that can be divided by 5 pins between 1-1000, and output 3 for each line
for(int i=1;i<=1000;i++){
    if(i%5==0){
        system.out.print(i+"\t");
    }
    if(i%(5*3)==0){ //3 line breaks per line
        system.out.println();//Method 1
        system.out.print("\n");//Method 2
    }
}
//println will wrap automatically after output
//No line wrapping after print output

//Exercise 3: print the 99 multiplication table
/*
1. Print the first column first;
2. Wrap the fixed 1 in a cycle;
3. Remove duplicate items, I < = J;
4. Adjust the style.
*/
for(int j=1; j<=9; j++){
    for(int i=1; i<=j; i++){
    System.out.print(j+"*"+i+"="+(j*i)+ "\t");//nowrap 
	}
    System.out.println();//Line feed
}

4) Enhanced for loop

Java 5 introduces an enhanced for loop that is primarily used for arrays or collections

for(Declaration statements: expressions)
{
    //Execute code
}
//Example: traversing the elements of an array
int[] numbers = {10,20,30,40,50};//Define an array
for(int x:numbers){
    System.out.println(x);//Output array data
}
//Equivalent to
for(int i=0; i<5; i++){
    System.out.println(numbers[i]);
}
  • 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: an expression is the name of the array to be accessed, or a method whose return value is an array.

5 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 sentences are also used in switch statements)
  • The continue statement is used in the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time.

About goto keyword (understand)

  • The goto keyword has long appeared in the programming language. Although goto is still a reserved word of Java, it has not been officially used in the language: Java does not have goto. However, we can still see some goto shadows in the two keywords break and continue - labeled break and 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 setting the label before the loop 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, they will interrupt to the place where the label exists.
//Print the prime number of lines between 1 and 150
//Prime number refers to a natural number that has no other factors except 1 and itself among natural numbers greater than 1.
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.print(i+" ");
}
//Exercise: printing 5 rows of triangles
for(int i=1; i<=5; i++){
    for(int j=5; j>=i; j--){
        System.out.print(" ");
    }
    for(int j=1; j<=i; j++){
        System.out.print("*");
    }
    for(int j=1; j<i; j++){
        System.out.print("*");
    }
    System.out.println();
}

Article source: Crazy God said Java video sorting

Crazy God said Java video learning address

Topics: Java