Javase Part 03: operators and process control of java basic syntax

Time:2020-11-9

This chapter will continue Part 02 of javase to explain in detail the operators in java basic syntax and the sequential structure and branch structure in process control.

Chapter 1: operators

Operators, in short, are symbols of operations.

The operations we usually understand are related to mathematics. Similarly, the operations in programming are consistent with the operation rules in mathematics.

In mathematics, we usually calculate numbers, while in programming, we calculate data.

If you want to operate, you must have the sign of operation.

1.1 – why operators are needed (understand)

From the perspective of application, in software development, there are many business functions that need to be realized through program calculation, such as:

  • Statistics and price calculation of online shopping goods
  • Consumption transfer of Alipay or WeChat
  • The calculation of life value and gold coin of game characters in the game

How to command a computer to calculate data? In this case, the operation symbol is needed to represent the operation.

Classification of 1.2-operators (understanding)

  • Assignment Operators
  • Arithmetic operator
  • Relational operators
  • Logical operator
  • Other Operators

1.3 – assignment operator (memory)

Operator format and function

  • Operation symbol:=
  • Function: can put the right side of thedata Assign todesignatedvariable

code

Int age = 10; // assign data 10 to variable age

1.4 – arithmetic operators (memory)

Operator format and function

  • Operation symbol:

    1. Represents addition operation+
    2. Denotes subtraction:-
    3. Represents the multiplication operation*
    4. Represents the division operation:/
    5. Denotes modular operation:%
  • Function: it can realize the operation of digital correlation

code

public static void main(String[] args) {
        int a = 10;
        int b = 3;
        /*Addition operation*/
        System.out.println(a + b);
        //Results: 13
        /*Subtraction*/
        System.out.println(a - b);
        //Results: 7
        /*Multiplication*/
        System.out.println(a * b);
        //Results: 30
        /*Division operation*/
        System.out.println(a / b);
        //Results: 3
        /*Modulo - remainder*/
        System.out.println(a % b);
        //Results: 1
        /*Note: in Java, any integer cannot be divided by 0, and an error will occur at runtime! * /
        System.out.println(200/0);
        //Results: exception in thread "main" java.lang.ArithmeticException : / by zero
}

1.5-relational operators (memory)

Relational operators are also called comparison operators

Operator format and function

  • Operator:

    • Greater than:>
    • Less than:<
    • be equal to:==
    • Greater than or equal to:>=
    • Less than or equal to:<=
    • Not equal to:!=
  • Function: it can realize conditional judgment, and the operation result is Boolean valuetrueorfalse

code

public static void main(String[] args) {
        int a = 10;
        int b = 12;
        /*Greater than*/
        System.out.println(a > b);
        //Results: false
        /*Less than*/
        System.out.println(a < b);
        //Results: true
        /*Equal to*/
        System.out.println(a == b);
        //Results: false
        /*Greater than or equal to*/
        System.out.println(a >= b);
        //Results: false
        /*Less than or equal to*/
        System.out.println(a <= b);
        //Results: true
        /*Not equal to*/
        System.out.println(a != b);
        //Results: true
}

Note: do not mistakenly write “=” as “=”, which is the relationship of judging whether it is equal or not, and “=” is the assignment.

1.6 – logical operators (memory)

The format and function of logical operators

Javase Part 03: operators and process control of java basic syntax

The logical operator can judge whether multiple combination conditions are true or not, and the operation result is a Boolean value: true or false

code

public class Operator {
    public static void main(String[]args){
        //Defining variables 
        int i = 100; 
        int j = 200; 
        int k = 300; 
        //&As long as one value in the expression is false, the result is false
        System.out.println ((I > J) & (I > k)); // false & false, output false
        System.out.println ((I < J) & (I > k)); // true & false, output false
        System.out.println ((I > J) & (I < K)); // false & true, output false
        System.out.println ((I < J) & (I < K)); // true & true, output true
        //|"Or", or relationship, as long as one value in the expression is true, the result is true
        System.out.println ((I > J) | (I > k)); // false | false, output false
        System.out.println ((I < J) | (I > k)); // true | false, output true
        System.out.println ((I > J) | (I < K)); // false | true, output true
        System.out.println ((I < J) | (I < K)); // true | true, output true
        //^"XOR", the same is false, but different is true 
        System.out.println ((I > J) ^ (I > k)); // false ^ false, output false
        System.out.println ((I < J) ^ (I > k)); // true ^ false, output true
        System.out.println ((I > J) ^ (I < K)); // false ^ true, output true
        System.out.println ((I < J) ^ (I < K)); // true ^ true, output false
        //! "non", negative
        System.out.println((i > j)); //false 
        System.out.println (! (I > J)); // false,, output true
    }
}

Short circuit logic operator

Javase Part 03: operators and process control of java basic syntax

In logic and operation, as long as the value of one expression is false, then the result can be judged as false. There is no need to calculate all the values of expression. Short circuit and operation have such effect and can improve efficiency.

Similarly, in a logical or operation, once the value is found to be true, the expression on the right will no longer participate in the operation

  • Logic and&Whether it is true or false on the left, it must be executed on the right.
  • Short circuit and&&If the left side is true, the right side will execute; if the left side is false, the right side will not execute.
  • Logical or|Whether it is true or false on the left, it must be executed on the right.
  • Short circuit or||If the left side is false, the right side will execute; if the left side is true, the right side will not execute.

code

public class Operator2 {
    public static void main(String[]args){
        int x = 3;
        int y = 4;
        System.out.println (((x = x + 1) > 4) & ((y = y + 1) > 5)); // both expressions can operate 
        System.out.println(x); // 4 
        System.out.println(y); // 5 
        int a = 3;
        int b = 4;
        System.out.println (((a = a + 1) > 4) & & ((b = B + 1) > 5)); // the left side can confirm that the result is false, and the right side does not participate in the operation
        System.out.println(a); // 4 
        System.out.println(b); // 4
    }
}

1.7 – other operators (memory)

  • compound assignment operators

    • Operator:+=-=/=*=%=
    • Function: related to variables, it is a combination of arithmetic operator and assignment operator.
    • code:
int age = 10;
    age+=3; 
    System.out.print(age); 
    //Results: 13. Age + = 3 disassembly age = AEG + 3
  • parentheses

    • Operator:(expression)
    • Function: can improve the priority of operation.
    • code:
    int result = (10 + 8) * 2
  • Self increasing and self decreasing

    • Operator:++--
    • Function: variable increases by 1 or decreases by 1

      • Self increase or decrease in front:++Variableor--Variable, let the variable itself add or subtract 1, and then participate in the expression operation.
      • Postposition self increase or decreaseVariable++orVariable--First, let the variable itself participate in the expression operation, and then add or subtract 1 by itself
    • code:
/*Pre increment*/
    int a = 10;
    System.out.print (+ + a); // result: 11
    System.out.print (a) ; // result: 11
    /*Post auto increment*/
    int b = 10;
    System.out.print (B + +); // result: 10
    System.out.print (b) ; // result: 11
  • Ternary operator

    • Format:Conditional expression? Expression 1: expression 2
    • Meaning: the position in front of the question mark is the judgment condition. If the judgment result is Boolean, expression 1 is called when it is true and expression 2 is called when it is false. The logic is: if the conditional expression is true or satisfied, the expression 1 will be executed; otherwise, the second one will be executed.
    • code:
int a = 10>8?10:8;
    System.out.print (a) ; // result: 10

Chapter 2: process control

2.0 – data input (understanding)

demand

Receive the two numbers entered by the user and calculate the sum of the two numbers.

Knowledge preparation: how to receive user input data

We can get the user’s input through the scanner class. The steps are as follows:

1. Guide package. Scanner class in java.util Package, so you need to import this class. The statement of the package guide needs to be defined on the top of the class.

import java.util.Scanner;

2. Create a scanner object.

Scanner sc = new Scanner( System.in ); // create the scanner object, SC represents the variable name, and the others are immutable

3. Receiving data

int i =  sc.nextInt (); // returns the value entered by the keyboard as an int.

4. Examples

import java.util.Scanner; 
public class ScannerDemo { 
    public static void main(String[] args) { 
        //Creating objects 
        Scanner sc = new Scanner(System.in); 
        //Receiving data 
        int x = sc.nextInt(); 
        //Output data 
        System.out.println("x:" + x); } 
}

Function realization:

import java.util.Scanner;
public class Test01 {
    public static void main(String[]args){
        //Create scanner object
        Scanner scanner = new Scanner(System.in);
        //Prompt for data
        System.out.println (please enter the first number:); 
        //Receive the first data entered by the user
        int num1 = scanner.nextInt();
        //Prompt for data
        System.out.println ("please enter the second number:)"; 
        //Receive the second data entered by the user
        int num2 = scanner.nextInt();
        //Calculate the sum of two numbers and output
        int sum = num1 + num2;
        //When any data is added to a string, "+" represents a connector
        System.out.println(num1 + "+" + num2 + "=" + sum);
    }
}

Output results

Please enter the first number:
100
Please enter the second number:
20
100+20=120

2.1 – why learn process control (understanding)

Process refers to the execution sequence of the program. The default execution order of the program is top-down.

However, in the program, some programs are executed selectively or repeatedly, and different choices will have different functions. For example, when we play games with King’s glory, when we choose different heroes on the mobile phone, the bottom layer is that the program is executing different codes.

Therefore, if you want to control the process of program execution, you must learn process control statements.

Process control statements can be divided into three categories: sequential structureBranching structureandCyclic structure.

In this chapter, we will study the sequential structure and branching structure, and the circular structure will be explained in detail in the next chapter.

2.2 – sequential structure (emphasis)

Sequence structure is the simplest and most basic flow control in a program, and there is no specific syntax structure,According to the code sequence, from top to bottom, from left to right, execute in turnThis is how most of the code in the program executes.

Sequence structure execution flow chart:

Javase Part 03: operators and process control of java basic syntax

public class Test {
    public static void main(String[]args){
        System.out.println(1); 
        System.out.println(2); 
        System.out.println(3); 
        System.out.println(4); 
    }
}
/*
    Implementation results:
    1
    2
    3
    4
*/

2.3 – branch structure (emphasis)

2.3.1 – if statement

Statement format:

If (conditional expression){
  //Code block
}

Implementation process:

If the conditional expression holds (the result is true), the program in the code block is executed.

Javase Part 03: operators and process control of java basic syntax

Example:

Requirement: receive the user’s input age, judge whether the user is over 18 years old, if over 18 years old, output “age legal”

import java.util.Scanner;
public class Test02 {
    public static void main(String[]args){
        //Create scanner object
        Scanner scanner = new Scanner(System.in);
        //Prompt for data
        System.out.println ("please enter your age"); 
        //Age of receiving user input
        int age = scanner.nextInt();
        //Judgment
        if(age >=18 ) {
            System.out.println ("legal age");
        }
    }
}

2.3.2 – if else statement

Statement format

If (conditional expression){
  //Code block
}else {
  //Code block
}

Execution process

If the conditional expression holds (the result is true), the program in the if code block is executed, and vice versa, the program in the else code block.

Javase Part 03: operators and process control of java basic syntax

Example:

Requirement: receive the user’s input age and judge whether the user is over 18 years old. If the user is over 18 years old, output “age legal”, otherwise output “illegal age”

import java.util.Scanner;
public class Test03 {
    public static void main(String[]args){
        //Create scanner object
        Scanner scanner = new Scanner(System.in);
        //Prompt for data
        System.out.println ("please enter your age"); 
        //Age of receiving user input
        int age = scanner.nextInt();
        //Judgment
        if(age >=18 ) {
            System.out.println ("legal age");
        }else {
            System.out.println ("age is illegal");
        }
    }
}

2.3.3 – if else if -… Else statement

Grammar format:

If (conditional expression){
  //Code block
}else If (conditional expression){   // 需求不同,else if语句定义的个数不同
  //Code block
}
else If (conditional expression){
  //Code block
}
// ...
Else {// different requirements, else statements are optional
  //Code block
}

Implementation process:

Code is judged from top to bottom.

If any of them meet the conditions, the code block for is executed, and the subsequent branches are not executed.

If none is satisfied, the statement in else is executed.

Javase Part 03: operators and process control of java basic syntax

Example:

Requirements: receive user input of academic performance, output level. If the score is greater than or equal to 90, it is a if the score is greater than or equal to 80, B is greater than or equal to 80, C is greater than or equal to 70, and D is greater than or equal to 60 and less than 70

import java.util.Scanner;
public class Test04 {
    public static void main(String[]args){
        //Create scanner object
        Scanner scanner = new Scanner(System.in);
        //Prompt for data
        System.out.println ("please enter student grade:"); 
        //Receive user input data
        float score = scanner.nextFloat();
        //Judgment
        if(score>=90) {
            System.out.println("A");
        }else if(score>=80) {
            System.out.println("B");
        }else if(score>=70) {
            System.out.println("C");
        }else if(score>=60) {
            System.out.println("D");
        }else{
            System.out.println("E");
        }
    }
}

2.3.4 – switch statement

Grammar format:

Switch (expression){ 
  Case constant value 1: 
    Sentence body 1;
    break;
  Case constant value 2:
    Sentence body 2;
    break; 
   //...
   default: 
    Sentence body n + 1; 
   break;
}

Implementation process:

First calculate the value of the expression

Secondly, compared with case, once there is a corresponding value, the corresponding statement will be executed. In the process of execution, if a break is encountered, it will end.

Finally, if all cases do not match the value of the expression, the body part of the default statement is executed and the program ends.

Javase Part 03: operators and process control of java basic syntax

Example 1:

Requirement: prompt the user to enter the number between 1 and 7, and return it to the user according to the data

import java.util.Scanner;
public class Test05 {
    public static void main(String[]args){
        //Create scanner object
        Scanner scanner = new Scanner(System.in);
        //Prompt for data
        System.out.println ("please enter a number (1-7):"); 
        //Receive user input data
        int num = scanner.nextInt();
        //Judgment
        switch (num){
            case 1:
                System.out.println ("Monday");
                break;
            case 2:
                System.out.println ("Tuesday");
                break;
            case 3:
                System.out.println ("Wednesday");
                break;
            case 4:
                System.out.println ("Thursday");
                break;
            case 5:
                System.out.println ("Friday");
                break;
            case 6:
                System.out.println ("Saturday");
                break;
            case 7:
                System.out.println ("Sunday");
                break;
            default:
                    System.out.println ("illegal");
                    break;
        }
    }
}

Example 2:

Demand: there are 12 months in a year, which belong to four seasons: spring, summer, autumn and winter. Enter a month by keyboard. Please use the program to determine which season the month belongs to and output it.

import java.util.Scanner;
public class Test06 {
    public static void main(String[]args){
        //Create scanner object
        Scanner scanner = new Scanner(System.in);
        //Prompt for data
        System.out.println ("please enter a month (1-12):"); 
        //Receive user input data
        int num = scanner.nextInt();
        //Judgment
        switch (num){
            case 12:
            case 1:
            case 2:
                System.out.println ("winter"); 
            break;
            case 3:
            case 4:
            case 5:
                System.out.println ("spring"); 
            break;
            case 6:
            case 7:
            case 8:
                System.out.println (the "summer"); 
            break;
            case 9:
            case 10:
            case 11:
                System.out.println ("autumn"); 
            break;
            default
                System.out.println ("the number entered is illegal"); 
            
        }
    }
}

Note: if the case in the switch does not correspond to a break, case penetration will occur.
Javase Part 03: operators and process control of java basic syntax