Java Process Control

1. User Interaction Scanner \quad Previously, the basic grammar we learned did not allow us to interact with programs a...
3.1 if single-selection structure
3.2 if double-selection structure
3.3 if multi-selection structure
3.4 Nested if Structure
3.5 switch multi-selection structure
3.6 Decompilation via IDEA
4.1 while Loop
4.2 do...while loop
4.3 for loop
4.4 Enhanced for Cycle
5.1 break keyword
5.2 continue keyword
5.3 Labels

1. User Interaction Scanner

\quad Previously, the basic grammar we learned did not allow us to interact with programs and people, but Java provided us with a tool class that allows us to get user input. java.util.Scanner is a new feature of Java5, and we can get user input through the Scanner class.

\quad First we need to import the class: import java.util.Scanner;. Then create a Scanner object, basic syntax: Scanner scan = new Scanner(System.in);. Then we can get the input string through the next() and nextLine() methods of the Scanner class. Before reading, we usually need to use hasNext() and hasNextLine() methods to determine whether there is input data. Finally, we want to close Scanner:scan.close();.

  • Note: 1. Classes belonging to IO streams will always consume resources if they are not closed. Turn them off if you want to develop a good habit.
    \ \ \quad    2. Calling the close method not only closes the Scanner class, but also closes the System.in object passed in as a parameter at initialization. Therefore, you can no longer use the Scanner class after close.

  • The difference between next() and nextLine()

    • next()
    1. You must read valid characters before you can finish typing.
    2. The next() method automatically removes any white space encountered before a valid character is entered.
    3. The white space entered after a valid character is used as a separator or terminator only after it has been entered.
    4. next() cannot get a string with spaces.
    • nextLine()
    1. The end character is Enter, which means that the nextLine() method returns all the characters before entering the carriage return.
    2. You can get blanks.

\quad If you are entering data of type int or float, it is also supported in the Scanner class, but it is best to validate it with the hasNextXxx() method before entering it, and then read it with nextXxx().

Scanner instance: Enter multiple numbers and sum and average them.

import java.util.Scanner; public class Demo03 { public static void main(String[] args) { int num = 2; double sum = 0.0; // Create a scanner object to receive keyboard data Scanner scanner = new Scanner(System.in); System.out.print("Please enter the first number:"); // Determine if the user has numeric input while (scanner.hasNextDouble()){ // Receive double type values using nextDouble double d = scanner.nextDouble(); System.out.print("Please enter #"+num+"Numbers:"); // Calculate Sum sum += d; // Count the total number of numbers entered num++; } System.out.println("Total Input"+(num-2)+"Numbers"); System.out.println("The sum of the input numbers:"+sum); System.out.println("Average:"+sum/(num-2)); } }

\quad Note: The hasNextXxx() method returns true if there is another tag in the input of this scanner. When standard input does not exist, the function blocks the process while waiting to read the input.
\quad In this case, you can set a terminator that calls the overloaded method hasNext(String patten) of hasNext(): Returns true if the next tag matches a pattern constructed from the specified string. The scanner does not perform any input. Examples are as follows:

while (!sc.hasNext("0")) { System.out.println(sc.next()); }
2. Sequential Structure
  • The sequence structure is the simplest in programming, as long as the corresponding statements are written in the order in which the problem is solved, it is executed from top to bottom, in turn.
  • The basic structure of Java is the sequential structure, which is executed one sentence at a time unless specifically specified.
  • Between a statement and a statement, the order between the box and the box is top-down. It is composed of several processing steps executed at one time. It is a basic algorithm structure that can not be separated from any algorithm.
3. Selection of Structure

3.1 if single-selection structure

  • Many times we need to decide if something is feasible before we can execute it, a process that is represented by an IF statement in a program.

  • Grammar:

    if (boolean_expression) { // Statement executed if Boolean expression is true }

3.2 if double-selection structure

  • Now there is a requirement that if the user enters a value greater than or equal to 60, he or she will fail. Such a requirement can be accomplished with one if. We need two judgments, a double-choice structure, and so an if-else structure.
  • Grammar:
    if (boolean_expression) { // If the Boolean expression is true, the statement executed. } else { // If the Boolean expression is false, the statement executed. }
  • Example:
    import java.util.Scanner; public class SelectionIfElse { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter your results:"); double score = scanner.nextDouble(); if (score >= 60) { System.out.println("pass"); } else { System.out.println("Fail"); } scanner.close(); } }

3.3 if multi-selection structure

  • We found that the code just now does not conform to the actual situation, the real situation may also exist A, B, C, D, there is interval multilevel judgment. Example: 90~100 is A; 80~90 is B... etc. In life, we have more than two choices, so we need a multi-choice structure to deal with this kind of problem!
  • Grammar:
    if (boolean_expression 1) { // The statement executed if the value of Boolean expression 1 is true. } else if (boolean_expression 2) { // Statement that is executed if the value of Boolean expression 2 is true. } else if (boolean_expression 3) { // The statement executed if the value of Boolean expression 3 is true. } ...... } else { // Statement to execute if none of the above Boolean expressions have true values. }
  • Example:
    import java.util.Scanner; public class SelectionIfElseIf { public static void main(String[] args) { // A test score greater than or equal to 60 is a pass, and a score less than 60 fails Scanner scanner = new Scanner(System.in); System.out.print("Please enter a result (0)~100): "); double score = scanner.nextDouble(); // Level Judgment if (score == 100) { System.out.println("Congratulations on the full score"); } 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 >=0 && score < 60) { System.out.println("Fail"); } else { System.out.println("Input results are illegal!"); } } }

3.4 Nested if Structure

  • It is legal to use nested if...else statements. That is, you can use if or else statements in another if or else if statement.
  • Grammar:
    if (boolean_expression 1) { // Executes when Boolean expression 1 is true if (boolean_expression 2) { // Executes when Boolean expression 2 is true } else if (boolean_expression 3) { // Executes when Boolean expression 2 is false and Boolean expression 3 is true } else { // Executes when Boolean expressions 2 and 3 are false } } else if (boolean_expression 4) { // Executes when Boolean expression 1 is false and Boolean expression 4 is true } else { // Executes when Boolean expressions 1 and 4 are false }

3.5 switch multi-selection structure

  • Another implementation of the multiple-choice structure is the switch case statement.
  • The switch case statement determines whether a variable is equal to a value in a series of values, each of which is called a branch.
  • Grammar:
    switch(expression){ case value : //Sentence break; //Optional case value : //Sentence break; //Optional //You can have any number of case statements default : //Optional //Sentence }
  • The switch case statement has the following rules:
    • Variable types in a switch statement can be byte, short, int, or char. Starting with Java SE 7, switch supports string String types, and the case tag must be string constant or literal.
    • A switch statement can have more than one case statement. Each case is followed by a value and colon to compare.
    • The value in a case statement must have the same data type as the variable and can only be a constant or literal constant.
    • When the value of a variable is equal to that of a case statement, the statement following the case statement begins execution and does not jump out of the switch statement until the break statement appears.
    • When a break statement is encountered, the switch statement terminates. The program jumps to the statement execution following the switch statement. A case statement does not have to contain a break statement. If no break statement appears, the program continues to execute the next case statement until a break statement appears.
    • A switch statement can contain a default branch, which is generally the last branch of the switch statement (it can be anywhere, but it is recommended that it be the last). Default is executed when the value of a variable is not equal to the value of a case statement. The default branch does not require a break statement.
  • Example:
    import java.util.Scanner; public class SwichCase { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the captain of the United States:"); String captainAmerica = scanner.nextLine(); switch (captainAmerica){ case "Steve Rogers": System.out.println("Captain America "+captainAmerica); break; case "Thor Odinson": System.out.println("Thor "+captainAmerica); break; case "Robert Bruce Banner": System.out.println("The Hulk "+captainAmerica); break; case "Natasha Romanoff": System.out.println("Black Widow "+captainAmerica); break; default: System.out.println("You entered:"+captainAmerica); } } }

3.6 Decompilation via IDEA

  • View the location of the compiled class file (settings) → \rightarrow → Project Structure... → \rightarrow → Project → \rightarrow → Project compiler output).

  • Open the folder where the class file is located (F:\IdeaProjects\JavaSE\out)
  • Copy the SwichCase.class file to the folder where the IDEA project is located (Note: You cannot operate directly in IDEA)

    import java.util.Scanner; public class SwichCase { public SwichCase() { } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the captain of the United States:"); String captainAmerica = scanner.nextLine(); byte var4 = -1; switch(captainAmerica.hashCode()) { case -644451191: if (captainAmerica.equals("Steve Rogers")) { var4 = 0; } break; case -178896433: if (captainAmerica.equals("Thor Odinson")) { var4 = 1; } break; case 2087830051: if (captainAmerica.equals("Robert Bruce Banner")) { var4 = 2; } break; case 2119186150: if (captainAmerica.equals("Natasha Romanoff")) { var4 = 3; } } switch(var4) { case 0: System.out.println("Captain America " + captainAmerica); break; case 1: System.out.println("Thor " + captainAmerica); break; case 2: System.out.println("The Hulk " + captainAmerica); break; case 3: System.out.println("Black Widow " + captainAmerica); break; default: System.out.println("You entered:" + captainAmerica); } } }
IV. Circular Structure

4.1 while Loop

  • while is the most basic loop, it is structured as:
    while(boolean_expression) { //Circular Content }
  • As long as the boolean_expression is true, the loop continues.
  • Most of the time we stop the loop, we need a way to invalidate the Boolean expression to end it.
  • In a few cases, loops need to be executed all the time, for example, server request response listening, etc.
  • A true loop condition always creates an infinite loop (an infinite loop), which we should try to avoid in normal business programming.

4.2 do...while loop

  • For a while statement, if the condition is not met, you cannot enter a loop. But sometimes we need to execute it at least once, even if the condition is not met. At this point, you need to use a do...while loop, which is structured as:
    do { // Code Statement } while(boolean_expression);
  • The do...while loop is similar to the while loop except that the Boolean expression of the do...while loop is behind the loop body, so the loop body has been executed before the Boolean expression is judged, so the do...while loop executes at least once. If the Boolean expression is true, the loop body executes until the Boolean expression is false.
  • The difference between a while loop and a do...while loop:
    • The while loop first determines the Boolean expression and then executes the loop body. do...while loops execute the loop body and then determine the Boolean expression.
    • do...while loops always guarantee that the loop body will be executed at least once.

4.3 for loop

  • Although all loop structures can be represented with while or do...while, Java provides another statement, the for loop, which makes some loop structures simpler.
  • The number of times a for loop is executed is determined before execution. The grammar format is as follows:
    for(Initialization; Boolean expression; To update) { //Code Statement }
  • There are several explanations about the for loop:
    • Initialization steps are performed first. A type can be declared, but one or more loop control variables can be initialized, or an empty statement can be made.
    • It then detects the value of the Boolean expression, which can be an empty statement. If true, the loop body is executed. If false, the loop terminates and the statement following the loop body begins to execute.
    • After a loop is executed, the loop control variable is updated without updating, which is an empty statement.
    • Detect the Boolean expression again. The loop executes the above procedure.
  • Example: Print a 99 multiplication table.
    public class ForDemo03 { public static void main(String[] args) { for (int i = 1; i < 10; i++) { for (int j = 1; j < 10; j++) { if (j <= i) { System.out.printf("%d x %d = ", i, j); System.out.print(i*j+",\t"); } else { break; } } System.out.println(); } } }

4.4 Enhanced for Cycle

  • Let's take a brief look here and focus on the array that follows.
  • Java 5 introduces an enhanced for loop, mainly for arrays or collections.
  • The Java enhanced for loop syntax format is as follows:
    for (Declare Statement : Expression) { //Code Sentences }
    • Declare statement: Declare a new local variable whose type must match the type of the array element. Its field of action is limited to the loop statement block, and its value is equal to that of the array element at this time.
    • Expression: An expression is the name of an array to access or a method that returns an array.
  • Example: Traverse through array elements.
    public class ForEach { public static void main(String[] args) { int num = 1; int[] numArray = ; for (int i : numArray) { System.out.println("No. "+num+" Elements:"+i); num++; } } }
5. break & continue

5.1 break keyword

  • break is used primarily in looping or switch ing statements to jump out of an entire statement block.
  • break is used to force a jump out of the innermost loop without executing the remaining statements in the loop, and then proceed with the statements outside the loop.

5.2 continue keyword

  • continue applies to any circular control structure. The purpose is to let the program terminate a loop by skipping statements that have not been executed in the loop body and jumping directly to the next iteration of the loop.
  • In the for loop, the continue statement causes the program to jump to the update statement immediately.
  • In a while or do...while loop, the program immediately jumps to the judgment statement of a Boolean expression.

5.3 Labels

  • Labels in Java must precede loops and must follow loops closely. Labels are designed for loops and are designed to facilitate the use of break s and coutinue s in multiple loops.
  • Labeled loops actually give this loop a name, and when you use the "continue (or break) + label" statement, you are actually executing the continue (or break) statement in the loop in which the label resides.
  • Labels must be placed before loops and must follow loops closely.
  • When using break lable to jump, you can only jump from the inner layer to the outer statement block, not from the outer layer to the inner or parallel code block.
  • A labeled break is a statement that jumps out of the loop to the label label and continues to execute the label label corresponding to the back of the loop body. A labeled continue is the next cycle in which label labels correspond directly to the loop body.
  • Note: Tagged break and coutinue implements functionality similar to the goto keyword in other design languages, but goto is a reserved word in Java and is not formally used in the language.
  • Example:
    • break lable
      public class LabelDemo01 { public static void main(String[] args) { out: for(int i = 0; i < 10; i++){ System.out.println(); for(int j = 0; j < 10; j++){ if(j == 5){ break out; } System.out.print("("+i+","+j+") "); } } System.out.println("End"); } } // Output results: (0,0) (0,1) (0,2) (0,3) (0,4) End
    • continue lable
      public class LabelDemo02 { public static void main(String[] args) { out: for(int i = 0; i < 10; i++){ System.out.println(); for(int j = 0; j < 10; j++){ if(j == 5){ continue out; } System.out.print("("+i+","+j+") "); } } System.out.println("End"); } } // Output results: // (0,0) (0,1) (0,2) (0,3) (0,4) // (1,0) (1,1) (1,2) (1,3) (1,4) // (2,0) (2,1) (2,2) (2,3) (2,4) // (3,0) (3,1) (3,2) (3,3) (3,4) // (4,0) (4,1) (4,2) (4,3) (4,4) // (5,0) (5,1) (5,2) (5,3) (5,4) // (6,0) (6,1) (6,2) (6,3) (6,4) // (7,0) (7,1) (7,2) (7,3) (7,4) // (8,0) (8,1) (8,2) (8,3) (8,4) // (9,0) (9,1) (9,2) (9,3) (9,4) End

19 November 2021, 21:54 | Views: 5233

Add new comment

For adding a comment, please log in
or create account

0 comments