Java process control

Posted by Lodar on Fri, 11 Feb 2022 12:45:53 +0100

Process control

Scanner object

  • In the basic syntax we learned before, we didn't realize the interaction between programs and people, but Java provides us with such a tool class that we can get the user's input. java.util.Scanner is a new feature of Java 5. We can get user input through scanner class.

  • 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.

    • 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 entering a valid character will the blank space after it be used as the separator or terminator.
      4. next() cannot get a string with spaces.
      //Create a scanner object to receive keyboard data
      Scanner s=new Scanner(System.in);
      
      System.out.println("use next Reception mode:");
      
      //Judge whether the user has entered a string
      if (s.hasNext()) {
          //Receive in next mode
          String str=s.next();//The program will wait for the user to complete the input
          System.out.println("The output contents are:"+str);
      }
      //All classes belonging to IO streams will always occupy resources if they are not closed. Form a good habit and close them when they are used up
      s.close();
      
    • 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.
      //Create a scanner object to receive keyboard data
      Scanner s=new Scanner(System.in);
      
      System.out.println("use nextLine Reception mode:");
      
      //Judge whether the user has entered a string
      if (s.hasNextLine()) {
          //Receive using nextLine
          String str=s.nextLine();//The program will wait for the user to complete the input
          System.out.println("The output contents are:"+str);
      }
      //All classes belonging to IO streams will always occupy resources if they are not closed. Form a good habit and close them when they are used up
      s.close();
      
    • hasNextInt() determines whether it is an integer

    • hasNextFloat() determines whether it is a decimal

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 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.

Select structure

  1. if single conditional structure

    • grammar

      if (Boolean expression){
          //The statement that will be executed if the Boolean expression is true
      }
      
      Scanner scanner=new Scanner(System.in);
      System.out.println("Please enter:");
      String s=scanner.nextLine();
      
      //equals: determines whether the strings are equal
      if (s.equals("Hello")){
          System.out.println(s);
      }
      
      System.out.println("End");
      scanner.close();
      
  2. if double conditional 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 multi conditional structure

    • grammar

      if (Boolean expression 1){
          //Statement to execute if Boolean expression 1 is true
      }else if (Boolean expression 2){
          //Statement to execute if Boolean expression 2 is true
      }else if (Boolean expression 3){
          //Statement to execute if Boolean expression 3 is true
      }else{
          //The statement that will be executed if none of the 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 multiple selection structure

    • Another implementation method of multi selection structure is switch case statement.

    • The value of each switch statement is equal to that of a case in a series of statements.

    • The variable types in the switch statement can be:

      • byte, short, int or char.
      • Start with Java SE 7
      • switch supports String type
      • At the same time, the case tag must be a string constant or literal.
    • grammar

      switch (expression){
          case value:
              //sentence
              break;//Optional
          case value:
              //sentence
              break;//Optional
          //There can be any number of case statements
          default://Optional
              //sentence
      }
      

Cyclic structure

  • while Loop

    • while is the most basic loop. Its structure is:

      while (Boolean expression){
          //Cyclic content
      }
      
      //Calculate 1 + 2 + 3 ++ 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 request response listening of the server.

    • 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!

  • 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);
      
      //Calculate 1 + 2 + 3 ++ 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 is judged before execution. do... while is to execute first and then judge!
      • Do... while always ensures that the loop is executed at least once! This is their main difference.
  • 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.

    • The number of times the for loop is executed is determined before execution. The syntax format is as follows:

      for (initialization;Boolean expression;to update){
          //Code statement
      }
      
      int a=1;//Initialization condition
      while (a<=100){//Conditional judgment
          System.out.println(a);//Circulatory body
          a+=2;//iteration
      }
      System.out.println("while End of cycle!");
      System.out.println("=============================");
      
      //Initialize / / condition judgment / / iteration
      for (int i=1;i<=100;i++){
          System.out.println(i);
      }
      System.out.println("for End of cycle!");
      
    • Q

  • Enhanced for loop

    • Here, we just meet and understand, and then we focus on the use of arrays

    • Java 5 introduces an enhanced for loop that is mainly used for arrays or collections.

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

      for (Declaration statement:expression){
          //Code sentence
      }
      
      int[] numbers={10,20,30,40};//Defines an array
      //Traversing the elements of an array
      for (int x:numbers){
          System.out.println(x);
      }
      
    • 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.

break and 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 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

    • Goto keyword has long appeared in programming languages. Although goto is still a reserved word of Java, it has not been officially used in the language; Java has no goto. However, in the two keywords break and continue, we can still see some shadow of goto - labeled break and continue.

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

      //Print all prime numbers between 101 - 150
      //Prime number refers to a natural number that has no other factors except 1 and itself among natural numbers greater than 1.
      outer:for (int i=101;i<=150;i++){//Jump here
          for (int j=2;j<i/2;j++){
              if (i%j==0){
                  continue outer;//The outer here can be changed, and the program will jump to the beginning when it comes here
              }
          }
          System.out.print(i+" ");
      }
      
    • For Java, the only place where tags are used is before loop statements. The only reason to set the label before the loop is that we want to nest another loop in it. Because the break and continue keywords usually only break the current loop, but if they are used with the label, they will break to the place where the label exists.

Topics: Java Back-end