Basic java learning -- Chapter 2 basic Java syntax

Posted by iKwak on Tue, 08 Mar 2022 03:32:15 +0100

Basic java learning -- Chapter 2 basic Java syntax

1, Keywords and identifiers

1. Definition of identifier

All places where you can name yourself are called identifiers, such as class name, variable name, method name, interface name, package name

2. Naming rules of identifiers

(if it is not complied with, the compilation fails)

  1. It consists of 26 English letters in case, 0-9_ Or & Composition
  2. Number cannot start
  3. Keywords and reserved words cannot be used, but they can be included
  4. Java is strictly case sensitive and has unlimited length
  5. The identifier cannot contain spaces

3. Naming conventions in Java

(if not, the compilation can pass, and it is recommended to comply)

  1. Package name: all letters are lowercase when composed of multiple words xxxyyzzzz
  2. Class name and interface name: when composed of multiple words, the first letter of all words is capitalized xxyyyzz (big hump)
  3. Variable name and method name: when composed of multiple words, the first word is lowercase, and the first letter of each word is uppercase xxyyyzz (small hump) at the beginning of the second word
  4. Constant name: all letters are capitalized. When there are multiple words, each word is connected with an underscore_ YYY_ ZZZ

2, Use of variables

1. Use of variables

1) Java defines the format of variables
//First kind
 Data type variable name = Variable value;
//Second
 Data type variable name;
Variable name = Variable value;
2) Explain
  1. Variables must be declared before use
  2. Variables are defined within their scope. Within the scope (i.e. {}), it is valid; Out of scope, it is invalid
  3. Two variables with the same name cannot be declared in the same scope

2. Classification of variables

1) By data type
  1. Basic data types (8 kinds):
  • Integer: byte(1 byte = 8bit) \ short(2 bytes) \ int(4 bytes, the default integer constant of Java is int) \ long(8 bytes)
    Note: to define a long variable, it must end with "L" or "L"
  • Floating point type: float(4 bytes) \ double(8 bytes, the floating point constant of Java is double by default)
    Note: to define a float type variable, it must end with "F" or "F"
  • Character type: char(2 bytes) single quotation mark
  • Boolean: Boolean (only true and false can be taken)
  1. Reference data type:
  • A common type of string is string
  • Interface
  • Array
2) Position declared in the class by variable
  1. Member variables: variables declared outside the method and inside the class
  • Instance variable (not decorated with static)
  • Class variable (decorated with static)
  1. Local variable: a variable declared inside a method body
  • Formal parameters (variables defined in methods and constructors)
  • Method local variable (defined within the method)
  • Code block local variables (defined within the code block)

3. Operation rules between basic data types (excluding boolean type)

1) Automatic type lifting
  1. When the variable of the data type with small capacity is calculated with the variable of the data type with large capacity, the result will be automatically promoted to the data type with large capacity (Note: the capacity refers to the size of the range of numbers represented by the data type, for example, the capacity of float is greater than that of long)
  2. Data types are sorted by capacity:
    byte \ char \ short --> int --> long --> float --> double
  • In particular: byte, char and short will not be converted to each other. They will be converted into int type first when calculating (even if two byte type variables operate, the result will be int type)
2) Cast: inverse operation of automatic type promotion
  1. The cast character '()' is required
  2. Casting data types can result in loss of precision
  • Capacity refers to the size of the range of numbers represented by the data type. For example, the capacity of float is greater than that of long
3) Integer constant. The default type is int; Floating point constant. The default type is double
public class Day02_VariableTest {
    public static void main(String[] args) {
        //Definition of variables
        int myAge = 12;
        //Use of variables
        System.out.println(myAge);

        //Compilation error: variables are not defined before use
        //System.out.println(myNumber);

        //Declaration of variables
        int myNumber;

        //Compilation error: a variable was not assigned a value before it was used
        //System.out.println(myNumber);

        //Assignment of variables
        myNumber = 1000;
        System.out.println(myNumber);

        //******************************Automatic type lifting
        byte b1 = 2;
        int i1 = 129;
        //Compilation failed
        //byte b2 = b1+i1;
        int i2 = b1 + i1;
        System.out.println(i2);

        char c1 = 'a'; //ASCII code is 97
        int i3 = 10;
        int i4 = c1 + i3;
        System.out.println(i4);

        short s2 = 10;
        //short s2 = c1 + s2; // Compilation failed
        //char c2 = c1 + s2; // Compilation failed

        byte b2 = 10;
        //char c3 = c1 + b2; // Compilation failed

        //******************************Cast type
        double d1 = 12.9;
        //Example of accuracy loss 1
        int i5 = (int)d1; //Truncation operation, using the cast character '()'
        System.out.println(i5);
        //No loss of accuracy
        long l1 = 123;
        short s3 = (short)l1;
        //Example of accuracy loss 2
        int i6 = 128;
        byte b = (byte)i6;
        System.out.println(b); //-128 binary decimal conversion, simple note: for byte type, the value range is - 128 ~ 127128, and the corresponding actual value should be - 128
        /*
        Why does it become - 128?
        int The binary original code of type 128 is: 0000 0000 0000 0000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000
        The computer uses complement to store data. The complement after forced conversion to byte type: 10 million
        Since the original code of - 127 is 1111 1111, the inverse code is 1000 0000 and the complement code is 1000 0001
        Therefore, the complement of - 128 is: 10 million
        Therefore, the decimal number after forced conversion to byte type is - 128
         */

        char c3 = '1'; //ASCII code is 49
        int c4 = (int)c3;
        System.out.println(c4); //49

        //******************************Define a long variable, which must end with "L" or "L"
        //Although the compilation will not report an error, at this time, the value without "L" on the right is an int value, which is assigned to the long variable l2, which is equivalent to the automatic type promotion
        long l2 = 123213;
        System.out.println(l2);

        //An error is reported during compilation, because "L" is not added on the right at this time. It is an int value, but the value exceeds the capacity range of int
        //long l3 = 1223231331312;
        //When "L" is added to the right, no error will be reported during compilation. At this time, a long value is assigned to the long variable l4 on the right
        long l4 = 1223231331312L;

        //******************************Define float type variable, which must end with "F" or "F"
        //If an error is reported during compilation and a float variable is defined, it must end with "F" or "F", because if "F" is not added on the right, the default value is double. Assigning a double value to a float variable will cause a loss of precision
        //float f1 = 12.3;
        //When "F" is added to the right, no error will be reported during compilation. At this time, a float type value is assigned to the float type variable f1 on the right
        float f1 = 12.3F;
        //Using cast, you can also assign a double value to a float variable
        float f2 = (float)12.3;

        //******************************Integer constant. The default type is int; Floating point constant. The default type is double
        byte b3 = 12;
        //Compilation reports an error, because the 1 on the right is an integer constant, and the default is int, so the operation result of b3 + 1 is also int (automatic type promotion). Assigning the value of int to the variable of byte will cause precision loss
        //byte b4 = b3 + 1;
        //Compilation reports an error, because 12.3 on the right is a floating-point constant, which is double by default, and the operation result of b3 + 12.3 is also double (automatic type promotion). Assigning the value of double to the variable of float will cause precision loss
        //float f1 = b3 + 12.3;
    }
}

4. Use of string type variable

  1. String is not a basic data type, but a reference data type
  2. Use a pair of '' when declaring a variable of type String
  3. String can operate with 8 basic data type variables, and can only perform connection operation '+', and the result of operation is still string type
public class Day02_StringTest {
    public static void main(String[] args) {
        String s1 = "HelloWorld";
        System.out.println(s1);
        String s2 = "a";
        //Empty string
        String s3 = "";
        //Compilation error, char type variable must contain one character
        //char c = '';

        //***************************String and 8 basic data type variables' + '
        int number = 1001;
        String numberStr = "Student number:";
        String info = numberStr + number;

        boolean b1 = true;
        String info1 = info + b1;
        System.out.println(info1);

        //***************************Exercise 1
        char c = 'a'; //ASCII code is 97
        int num = 10;
        String str = "hello";
        System.out.println(c + num + str); //107hello
        System.out.println(c + str + num); //ahello10
        System.out.println(c + (num + str)); //a10hello
        System.out.println((c + num) + str); //107hello
        System.out.println(str + num + c); //hello10a

        //***************************Exercise 1
        //*    *
        System.out.println("*    *"); //*    *
        System.out.println('*' + '\t' + '*'); //93
        System.out.println('*' + "\t" + '*'); //*    *
        System.out.println('*' + '\t' + "*"); //51*
        System.out.println('*' + ('\t' + "*")); //*    *

        //***************************Exercise 3
        //Compilation failed. 123 is an int value and cannot be assigned to a String variable. You need to add "", that is, int cannot be converted to String
        //String str1 = 123;
        String str1 = "123";
        String str2 = 123 + "";
        System.out.println(str2); //The output "123" is of string type

        //Both of the following methods fail to compile because String type cannot be converted to int type
        //int num1 = str1;
        //int num1 = (int)str1;

        int num1 = Integer.parseInt(str1);
        System.out.println(num1); //Output 123 is int type
    }
}

3, Operator

1. Arithmetic operator

1) Common arithmetic operators
  1. +(plus sign)
  2. -(minus sign)
  3. +(plus)
  4. -(less)
  5. *(by)
  6. /(except)
  7. %(mold / residue)
  8. (front) + + (rear)++
  9. (front) - (rear) -
  10. +(string connection)
  • Note: self increment and self decrement will not change the data type of the variable itself
public class Day03_AriTest {
    public static void main(String[] args) {
        //******************************Except:/
        int num1 = 12;
        int num2 = 5;
        int result1 = num1 / num2;
        System.out.println(result1); //2

        int result2 = num1 / num2 * num2;
        System.out.println(result2); //10 from front to back

        double result3 = num1 / num2;
        System.out.println(result3); //2.0 the result of the operation on the right is the value 2 of int type, and then assign the value of int type to the variable of double type, so the value of this variable is 2.0

        double result4 = num1 / num2 + 0.0;
        System.out.println(result4); //On the right side of 2.0, first calculate num1 / num2, and the result is the value 2 of int type, then add 0.0, and the result is the value 2.0 of double type

        double result5 = num1 / (num2 + 0.0);
        System.out.println(result5); //2.4 on the right, the result of calculating (num2 + 0.0) is the value of double 5.0, and then the result of calculating num1 / (num2 + 0.0) is the value of double 2.4

        double result6 = (double)num1 / num2;
        System.out.println(result6); //2.4 strongly convert num1 to double type. At this time, the result of calculating num1 / num2 is the value of double type 2.4

        double result7 = (double)(num1 / num2);
        System.out.println(result7); //2.0 on the right side, first calculate num1 / num2, and the result is the value 2 of int type, and then strongly convert to the value 2.0 of double type

        //******************************Mold / residue extraction:%
        //Note: the result of modulo operation is the same as the symbol of modulo
        //Often use% to judge whether it can be divided
        int m1 = 12;
        int n1 = 5;
        System.out.println("m1 % n1 = " + m1 % n1); //2

        int m2 = -12;
        int n2 = 5;
        System.out.println("m2 % n2 = " + m2 % n2); //-2

        int m3 = 12;
        int n3 = -5;
        System.out.println("m3 % n3 = " + m3 % n3); //2

        int m4 = -12;
        int n4 = -5;
        System.out.println("m4 % n4 = " + m4 % n4); //-2

        //******************************Self increasing 1:++
        //(front) + +: increase by 1 first, and then calculate the assignment
        int a1 = 10;
        int b1 = ++a1;
        System.out.println("a1 = " + a1 + ", b1 = " + b1); //11, 11

        //(later) + +: first calculate the assignment, and then increase by 1
        int a2 = 10;
        int b2 = a2++;
        System.out.println("a2 = " + a2 + ", b2 = " + b2); //11, 10

        int a3 = 10;
        a3++; //++a3;
        int b3 = a3;
        System.out.println(b3); //11

        //Note: the auto increment operation will not change the data type of the variable
        short s1 = 10;
        //s1 = s1 + 1; // Compilation failed, because byte, char and short will not be converted to each other, and they will be converted into int type first during calculation. Therefore, the operation result on the right is the value of int type, and the variables assigned to short type will have precision loss
        //s1 = (short)(s1 + 1); // Compiled successfully, but not commonly used
        s1++; //Auto increment 1 will not change the data type of the variable itself. It is recommended to use auto increment
        System.out.println(s1); //1

        //Question:
        byte byte1 = 127;
        byte1++;
        System.out.println(byte1); //-128

        //******************************Self subtraction 1:--
        //(front) --: subtract 1 first and then assign value
        //(later) --: assign value first, and then subtract 1
        int a4 = 10;
        int b4 = a4--;
        System.out.println("a4 = " + a4 + ", b4 = " + b4); //9, 10
    }
}

Exercise: give an integer at will, print and display its single digit, ten digit and hundred digit values. The format is as follows:
The number xxx is as follows:
Single digit:
Ten digits:
Hundredths:

public class Day03_AriExer {
    public static void main(String[] args) {
        int num = 187;
        int a = num / 100;
        int b = num % 100 / 10; //int b = num / 10 % 10
        int c = num % 10;
        System.out.println("number" + num + "The situation is as follows:");
        System.out.println("Single digit:" + c);
        System.out.println("Ten digits:" + b);
        System.out.println("White digit:" + a);
    }
}

2. Assignment operator

2) Common assignment operators
  1. =
  2. +=
  3. -=
  4. *=
  5. /=
  6. %=
public class Day03_SetValueTest {
    public static void main(String[] args) {
        //******************************Assignment symbol:=
        int i1 = 10;
        int j1 = 10;

        int i2, j2;
        //continuous assignment 
        i2 = j2 = 10;

        int i3 = 10, j3 = 20;

        //******************************Assignment symbol: + = - = * = / =% = the data type of the variable itself will not be changed
        int num1 = 10;
        num1 += 2; //num = num + 2;
        System.out.println(num1); //12

        short s1 = 10;
        //s1 = s1 + 2; // Compilation failed
        s1 += 2; //Compiled successfully
        System.out.println(s1);

        //In development, if you want the variable to realize the operation of + 2, how many methods are there? (premise: int num = 10;)
        //Method 1: num = num + 2;
        //Mode 2: num += 2; (recommended. The data type will not be changed. Even if the variable is not of int type, it can be compiled successfully)

        //In development, if you want the variable to realize the operation of + 1, how many methods are there? (premise: int num = 10;)
        //Method 1: num = num + 1;
        //Mode 2: num += 1;
        //Mode 3: num + +; (recommended, the data type will not be changed. Even if the variable is not of int type, it can be compiled successfully; compared with mode 2, the amount of code is less)

        //Exercise 1
        int i = 1;
        i *= 0.1;
        System.out.println(i); //0, * = does not change the data type of the variable
        i++;
        System.out.println(i); //1

        //Exercise 2
        int m = 2;
        int n = 3;
        n *= m++; //n = n * m++;
        System.out.println("m=" + m); //3
        System.out.println("n=" + n); //6

        //Exercise 3
        int n1 = 10;
        n1 += (n1++) + (++n1); //n1 = n1 + (n1++) + (++n1);
        System.out.println(n1); //10 + 10 + 12 = 32
    }
}

3. Comparison operator

1) Common comparison operators
  1. ==
  2. !=
  3. >
  4. <
  5. >=
  6. <=
  7. instanceof
2) Conclusion
  1. The result of the comparison operator is a boolean type
  2. Distinguish between = = and=
public class Day03_CompareTest {
    public static void main(String[] args) {
        int i = 10;
        int j = 20;
        System.out.println(i == j); //false
        System.out.println(i = j); //20

        boolean b1 = true;
        boolean b2 = false;
        System.out.println(b2  == b1); //false
        System.out.println(b2 = b1); //true
    }
}

4. Logical operators

1) Common logical operators
  1. &(logic and)
  2. &&(short circuit and)
  3. |(logical or)
  4. ||(short circuit or)
  5. ! (logical non)
  6. ^(logical XOR)

Logical operators operate on variables of boolean type, and the result is also of boolean type

public class Day03_LogicTest {
    public static void main(String[] args) {
        //Distinguish & and&&
        //Same point 1: & and & & have the same operation results
        //Same point 2: when the left side of the symbol is true, both will perform the operation on the right side of the symbol
        //Difference 1: when the left side of the symbol is false, & will still perform the operation on the right side of the symbol, while & & will not perform the operation on the right side of the symbol (because the left side of the symbol is false, no matter what the right side of the symbol is, the final result must be false, which is equivalent to that the right side of the symbol is short circuited, so it will not be performed)
        //During development, it is recommended to use & & (short circuit and)
        boolean b1 = true;
        b1 = false;
        int num1 = 10;
        if (b1 & (num1++ > 0)) {
            System.out.println("I'm in Beijing now"); //When the left side of the symbol is false, & the operation on the right side of the symbol will still be performed
        } else {
            System.out.println("I'm in Nanjing now");
        }
        System.out.println("num1=" + num1); //11

        boolean b2 = true;
        b2 = false;
        int num2 = 10;
        if (b2 && (num2++ > 0)) {
            System.out.println("I'm in Beijing now"); //When the left side of the symbol is false, & & will not perform the operation on the right side of the symbol
        } else {
            System.out.println("I'm in Nanjing now");
        }
        System.out.println("num2=" + num2); //10

        //Distinguish between | and||
        //Same point 1: the operation results of | and | are the same
        //Same point 2: when the left side of the symbol is false, both will perform the operation on the right side of the symbol
        //Difference 1: when the left side of the symbol is true, | will still perform the operation on the right side of the symbol, but | will not perform the operation on the right side of the symbol (because the left side of the symbol is true, no matter what the right side of the symbol is, the final result must be true, which is equivalent to that the right side of the symbol is short circuited, so it will not be performed)
        //In development, it is recommended to use | (short circuit or)
        boolean b3 = false;
        b3 = true;
        int num3 = 10;
        if (b3 | (num3++ > 0)) {
            System.out.println("I'm in Beijing now"); //When the left side of the symbol is false, & the operation on the right side of the symbol will still be performed
        } else {
            System.out.println("I'm in Nanjing now");
        }
        System.out.println("num3=" + num3); //11

        boolean b4 = false;
        b4 = true;
        int num4 = 10;
        if (b4 || (num4++ > 0)) {
            System.out.println("I'm in Beijing now"); //When the left side of the symbol is false, & the operation on the right side of the symbol will still be performed
        } else {
            System.out.println("I'm in Nanjing now");
        }
        System.out.println("num4=" + num4); //10
    }
}

5. Bitwise operator

1) Explain
  1. Bitwise operators operate on integer data
  2. < <: within a certain range, every shift to the left is equivalent to * 2
    >>: within a certain range, each shift to the right is equivalent to / 2
  3. Interview question: the most efficient way to calculate 2 * 8?
    2 < < 3 or 8 < < 1
public class Day03_BitTest {
    public static void main(String[] args) {
        int i = 21;
        System.out.println("i << 2:" + (i << 2)); //84

        int m = 12;
        int n = 5;
        System.out.println("m & n:" + (m & n));
        System.out.println("m | n:" + (m | n));
        System.out.println("m ^ n:" + (m ^ n));

        //Exercise: exchanging the values of two variables
        int num1 = 10;
        int num2 = 20;

        //Method 1: define temporary variables
        //int temp = num1;
        //num1 = num2;
        //num2 = temp;

        //Method 2: the advantage is that there is no need to define temporary variables
        //Disadvantages: the addition operation may exceed the storage range and is limited to numeric data, not applicable to strings
        //num1 = num1 + num2;
        //num2 = num1 - num2;
        //num1 = num1 - num2;

        //Method 3: use bitwise operators
        num1 = num1 ^ num2;
        num2 = num1 ^ num2;
        num1 = num1 ^ num2;
    }
}

6. Ternary operator

1) Structure

(conditional expression)? Expression 1: expression 2

2) Explain
  1. The result of the conditional expression is of type boolean
  2. Decide whether to execute expression 1 or expression 2 according to the true or false of the conditional expression
    If the expression is true, expression 1 is executed
    If the expression is false, expression 2 is executed
  3. Therefore, the data types of expression 1 and expression 2 should be unified into one type at least
  4. Ternary operators can be nested
  5. Where ternary operators can be used, they can be rewritten as if else. If the program can use both ternary operators and if else structure, the ternary operator is preferred. Reason: simplicity, high efficiency
public class Day03_SanYuanTest {
    public static void main(String[] args) {
        //Gets the larger value of two integers
        int m = 12;
        int n = 5;
        int max = (m > n) ? m : n;
        System.out.println(max);
        double num = (m > n) ? 2 : 1.0; //Expression 1 is of integer type and expression 2 is of double type. The results of both are of double type
        System.out.println(num);
        //(m > n)?  2: "n big"// Compilation error

        //Nested use of ternary operators
        n = 12;
        String maxstr = (m > n) ? "m large" : ((m == n) ? "m and n equal" : "n large");
        System.out.println(maxstr);

        //Gets the maximum of three numbers
        int n1 = 12;
        int n2 = 30;
        int n3 = -43;
        int maxValue = (n1 > n2) ? ((n1 > n3) ? n1 : n3) : ((n2 > n3) ? n2 : n3);
        System.out.println(maxValue);

        //Rewrite to if else:
        if (m > n) {
            System.out.println(m);
        } else {
            System.out.println(n);
        }

    }
}

4, Process control

1. Branch structure

a) If else (conditional judgment structure)

1) Three structures of if else
  1. First:
    if (conditional expression){
    Execute expression
    }

  2. Second: choose one from two
    if (conditional expression){
    Execute expression 1
    } else {
    Execute expression 2
    }

  3. Third: choose one more
    if (conditional expression){
    Execute expression 1
    }else if (conditional expression){
    Execute expression 2
    }else if (conditional expression){
    Execute expression 3
    } else {
    Execute expression 4
    }

2) Explain
  1. else structure is optional or not written
  2. For conditional expressions:
  • If multiple conditional expressions are mutually exclusive (without intersection), the order of judgment and execution statement declaration does not matter;
  • On the contrary, the order should be considered according to the actual situation
  • If there is an "include" relationship between multiple conditional expressions, the declaration with small scope is usually preceded
  • The data type of the conditional expression is boolean
  1. If else structures can be nested
  2. If the execution expression in the if else structure has only one line, the corresponding pair of {} can be omitted, but it is not recommended to omit
import java.util.Scanner;

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

        // Example 1: if the score is 100 points, a BMW will be rewarded; If the score is (80, 99), an iphone xs max will be rewarded; if the score is (60, 80), an ipad will be rewarded; otherwise, there will be no reward (requirement: input the score from the keyboard and judge it)
        System.out.println("Please enter your grade:");
        int score =  scan.nextInt();
        if (score == 100) {
            System.out.println("Reward one BMW");
        } else if ((score > 80) && (score <= 99)) {
            System.out.println("Reward one iphone xs max"); //Note: else if (80 < score < = 99) is not allowed because the result of calculating 80 < score from left to right is of boolean type and cannot be compared with 99 of int type
        } else if ((score > 60) && (score <= 80)) {
            System.out.println("Reward one ipad");
        } else {
            System.out.println("No reward");
        }

        // Example 2: input three integers into the variables num1, num2 and num3 by the keyboard, sort them (using if else), and output them from small to large
        System.out.println("Please enter the first integer:");
        int num1 = scan.nextInt();
        System.out.println("Please enter the second integer:");
        int num2 = scan.nextInt();
        System.out.println("Please enter the third integer:");
        int num3 = scan.nextInt();
        // The idea of occupying the grid: if num1 > num2, there are_ num2 _ num1 _, num3 can only appear in_ Location of
        if (num1 > num2) {
            if (num3 > num1) {
                System.out.println(num2 + ", " + num1 + ", " + num3);
            } else if (num3 < num2) {
                System.out.println(num3 + ", " + num2 + ", " + num1);
            } else {
                System.out.println(num2 + ", " + num3 + ", " + num1);
            }

        } else {
            if (num3 > num2) {
                System.out.println(num1 + ", " + num2 + ", " + num3);
            } else if (num3 < num1) {
                System.out.println(num3 + ", " + num1 + ", " + num2);
            } else {
                System.out.println(num1 + ", " + num3 + ", " + num2);
            }
        }

        //Example 3: each year of the first two years of a dog is equivalent to 10.5 years of human age, and then it will increase by 4 years every year. Write a program to obtain the age of the dog entered by the user, and display it through the program, which is equivalent to the age of human beings. If the user enters a negative number, please display a prompt information.
        System.out.println("Please enter the age of the dog:");
        int dogAge = scan.nextInt();
        double perAge = 0.0;
        if (dogAge < 0) {
            System.out.println("Wrong input. The dog's age is negative");
        } else {
            if (dogAge > 2) {
                perAge = 2 * 10.5 + 4 * (dogAge - 2);
            } else {
                perAge = dogAge * 10.5;
            }
        }
        System.out.println("The age of a dog is equivalent to that of a human being:" + perAge);

        //How to get an integer random number: 10-99
        //The formula generates an integer random number between [a, b]: (int)(Math.random() * (b - a + 1) + a)
        int value = (int)(Math.random() * 90 + 10); //[0.0, 1.0) ---> [0.0, 90.0) ---> [10.0, 100) ---> [10, 99]
        System.out.println(value);

        //Example 4: three conditions: 1) above 180cm; 2) More than 10 million; 3) Handsome; If the three conditions are met at the same time, "I must marry him!!!"; If the three conditions are true, then: "marry, less than the top, more than the bottom"; If the three conditions are not met, then: "do not marry!"
        System.out.println("Is your height above 180? ( true/false)");
        boolean case1 = scan.nextBoolean();
        System.out.println("Is the wealth more than 10 million? ( true/false)");
        boolean case2 = scan.nextBoolean();
        System.out.println("Handsome? ( true/false)");
        boolean case3 = scan.nextBoolean();
        if (case1 && case2 && case3) {
            System.out.println("I must marry him!!!");
        } else if (case1 || case2 || case3) {
            System.out.println("Marry, not enough than the top, more than the bottom.");
        } else {
            System.out.println("Don't marry!");
        }
    }
}

b) switch-case

1) Format of switch case

switch (expression){
case constant 1:
Execute statement 1;
//break;

case constant 2:
Execute statement 2;
//break;

...

default:
Execute statement n;
//break;
}

2) Explain
  1. Match the constants in each case in turn according to the value in the switch expression. Once the match is successful, the execution statement in the corresponding case structure is called. After the execution statement is called, the execution statement in other case structures will continue to be executed downward (the next case item penetrates, and there is no need to match the constants in other case structures at this time) until the break keyword is encountered or the switch case structure ends
  2. The break keyword can be used in the switch case structure. Once a break is encountered, it will directly jump out of the whole switch case structure
  3. The expression in the switch structure can only be one of the following six data types:
    byte, short, char, int, enumeration type variable (new in JDK5.0), String type (new in JDK7.0)
  4. After case, you can only declare constants, not ranges
  5. Default is equivalent to else of if else structure. The default structure is optional and the location is flexible
  6. If the execution statements of multiple cases in the switch case structure are the same, you can consider merging
import java.util.Scanner;

public class Day04_SwitchCaseTest {
    public static void main(String[] args) {
        int number = 2;
        switch (number) {
            case 0:
                System.out.println("zero");
                break;
            case 1:
                System.out.println("one");
                break;
            case 2:
                System.out.println("two");
                break;
            case 3:
                System.out.println("three");
                break;
            default:
                System.out.println("other");
                break;
        }
        Scanner scan = new Scanner(System.in);

//        //Example 1: for students with scores greater than 60, output "qualified"; If the score is lower than 60, the output is "unqualified"
//        System. out. Please enter "println";
//        int score = scan.nextInt();
//        //If the execution statements of multiple cases in the switch case structure are the same, you can consider merging
//        switch (score / 10) {
//            case 0:
//            case 1:
//            case 2:
//            case 3:
//            case 4:
//            case 5:
//                System.out.println("unqualified");
//                break;
//            case 6:
//            case 7:
//            case 8:
//            case 9:
//            case 10:
//                System.out.println("qualified");
//                break;
//        }
//        //Better solution
//        switch (score / 60) {
//            case 0:
//                System.out.println("fail");
//                break;
//            case 1:
//                System.out.println("qualified");
//                break;
//        }

//        //Example 2: input "month" and "day" of 2019 from the keyboard to judge the day of 2019
//        System.out.println("please output month:");
//        int month = scan.nextInt();
//        System.out.println("please output the date day:");
//        int day = scan.nextInt();
//        int sumDays = 0;
//        //Reduce redundancy with switch case (no break)
//        switch (month) {
//            case 12:
//                sumDays += 30;
//            case 11:
//                sumDays += 31;
//            case 10:
//                sumDays += 30;
//            case 9:
//                sumDays += 31;
//            case 8:
//                sumDays += 31;
//            case 7:
//                sumDays += 30;
//            case 6:
//                sumDays += 31;
//            case 5:
//                sumDays += 30;
//            case 4:
//                sumDays += 31;
//            case 3:
//                sumDays += 28;
//            case 2:
//                sumDays += 31;
//            case 1:
//                sumDays += day;
//        }
//        System.out.println(sumDays);

        //Example 3: input the year, month and day from the keyboard to judge the day of the year
        //      The criteria for judging leap years are: 1) it can be divided by 4, but not 100; 2) Or it can be divided by 400
        System.out.println("Please enter the year year:");
        int year = scan.nextInt();
        System.out.println("Please output the month month:");
        int month = scan.nextInt();
        System.out.println("Please output the date day:");
        int day = scan.nextInt();
        int sumDays = 0;
        //Reduce redundancy with switch case (no break)
        switch (month) {
            case 12:
                sumDays += 30;
            case 11:
                sumDays += 31;
            case 10:
                sumDays += 30;
            case 9:
                sumDays += 31;
            case 8:
                sumDays += 31;
            case 7:
                sumDays += 30;
            case 6:
                sumDays += 31;
            case 5:
                sumDays += 30;
            case 4:
                sumDays += 31;
            case 3:
                if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
                    sumDays += 29;
                } else {
                    sumDays += 28;
                }
            case 2:
                sumDays += 31;
            case 1:
                sumDays += day;
        }
        System.out.println(sumDays);
    }
}

Supplement: use of Scanner class

Get different types of variables from the keyboard (console)

  • Specific implementation steps:
  1. Guide Package:
import java.util.Scanner;
  1. Instantiation of Scanner:
    Variable type variable name = variable value (for classes, it is created by new)
Scanner scan = new Scanner(System.in);
  1. Call the relevant methods of the Scanner class to obtain the variables of the specified type
String info = scan.next();
int num = scan.nextInt();
import java.util.Scanner; //Guide Package

public class Day04_ScannerTest {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in); //Instantiate the scan object of a Scanner class
        System.out.println("Please enter your name:");
        String name = scan.next(); //Call the relevant methods of the Scanner class to obtain the variables of the specified type
        System.out.println(name);

        System.out.println("Please enter your age:");
        int age = scan.nextInt();
        System.out.println(age);

        System.out.println("Please enter your weight:");
        double weight = scan.nextDouble();
        System.out.println(weight);

        System.out.println("Do you like me? ( true/false)");
        boolean isLove = scan.nextBoolean();
        System.out.println(isLove);

        //For char type data, Scanner does not provide relevant methods, and can only obtain one string
        System.out.println("Please enter your gender: (male)/(female)");
        String gender = scan.next();
        char genderChar = gender.charAt(0); //Gets the character at position with index 0
        System.out.println(genderChar);
    }
}

2. Circulation structure

a) for loop

  • Four elements of circular structure:
    ① Initialization condition
    ② The loop condition -- > is of type boolean
    ③ Circulatory body
    ④ Iterative condition
1) Structure
for (① Initialization condition;② Cycle condition;④ Iterative condition)) {
    ③ Circulatory body
}
2) Execution process

① - > ② - > ③ - > ④ - > ② - > ③ - > ④ - >... - > ② (if the ② cycle condition is not met, the cycle ends)

public class Day05_ForTest {
    public static void main(String[] args) {
//        //Exercise 1
//        for (int i = 1; i <= 5; i++) {
//            System.out.println("HelloWorld");
//        }
//
//        //Exercise 2: ABC BC
//        int num = 1;
//        for (System.out.print('a'); num <= 3; System.out.print('c'), num++) {
//            System.out.print('b');
//        }
//        // System.out.println(i); //i is a local variable, which is only valid in the for loop, and it will fail out of the for loop
//
//        //Exercise 2: traverse even numbers within 100 and output the sum of all even numbers and the number of all even numbers
//        int sum = 0; // Record the sum of all even numbers
//        int count = 0; // Record the number of all even numbers
//        for (int i = 0; i <= 100; i++) {
//            if (i % 2 == 0) {
//                System.out.println(i);
//                sum += i;
//                count++;
//            }
//        }
//        System.out.println(sum);
//        System.out.println(count);

        //Exercise 3: cycle from 1 to 150 and print a value on each line. In addition, print "foo" on each multiple line of 3, "biz" on each multiple line of 5 and "baz" on each multiple line of 7,
        for (int i = 1; i <= 150; i++) {
            System.out.print(i);
            if (i % 3 == 0) {
                System.out.print(" foo");
            }
            if (i % 5 == 0) {
                System.out.print(" biz");
            }
            if (i % 7 == 0) {
                System.out.print(" baz");
            }
            System.out.println(); //Line feed
        }


    }
}

Exercise 4: enter two positive integers m and n to find their maximum common divisor and minimum common multiple (for example, the maximum common divisor of 12 and 20 is 4 and the minimum common multiple is 60). Explain the use of break keyword

import java.util.Scanner;
public class Day05_ForTest {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a positive integer m:");
        int m = scan.nextInt();
        System.out.println("Please enter a positive integer n:");
        int n = scan.nextInt();
        //Maximum common divisor: from large to small
        //Gets the smaller of the two numbers
        int smaller = (m <= n)? m : n;
        for (int i = smaller; i >= 1; i--) {
            if ((m % i == 0) && (n % i ==0)) {
                System.out.println("The maximum common divisor is: " + i);
                break;
            }
        }
        //Least common multiple: from small to large
        //Gets the maximum of the two numbers
        int bigger =  (m >= n)? m : n;
        for (int i = bigger; i <= m * n; i++) {
            if ((i % m == 0) && (i % n == 0)) {
                System.out.println("The least common multiple is: " + i);
                break;
            }
        }
    }
}

b) while loop

  • Four elements of circular structure:
    ① Initialization condition
    ② The loop condition -- > is of type boolean
    ③ Circulatory body
    ④ Iterative condition
1) Structure
① Initialization condition
while (② Cycle condition) {
	③ Circulatory body;
	④ Iterative condition;
}
2) Execution process

① - > ② - > ③ - > ④ - > ② - > ③ - > ④ - >... - > ② (if the ② cycle condition is not met, the cycle ends)

3) Explain
  1. When writing a while loop, be careful not to lose the iteration condition. Once lost, it may lead to an endless loop
  2. We need to avoid dead loops
  3. for loop and while loop can be transformed into each other!
    Difference: the scope of the two initialization conditions is different. The initialization conditions of the for loop are unavailable when the loop is out, while the while loop can still be called
public class Day05_WhileTest {
    public static void main(String[] args) {
        //Traverse all even numbers within 100
        //① Initialization condition
        int i = 0;
        //② Cycle condition
        while (i <= 100) {
            //③ Circulatory body
            if (i % 2 == 0) {
                System.out.println(i);
            }
            //④ Iterative condition
            i++;
        }

    }
}

c) Do while loop

  • Four elements of circular structure:
    ① Initialization condition
    ② The loop condition -- > is of type boolean
    ③ Circulatory body
    ④ Iterative condition
1) Structure
① Initialization condition
do {
	③ Circulatory body;
	④ Iterative condition;
} while (② Cycle condition);
2) Execution process

① - > ③ - > ④ - > ② - > ③ - > ④ - >... - > ② (if the ② cycle condition is not met, the cycle ends)

3) Explain
  1. The do while loop executes the loop body at least once
  2. Use for and while more and do while less in development
public class Day05_DoWhileTest {
    public static void main(String[] args) {
        //Traverse all even numbers within 100 and calculate the sum and number of all even numbers
        //① Initialization condition
        int i = 0;
        int sum = 0;
        int num = 0;
        do {
            //③ Circulatory body
            if (i % 2 == 0) {
                System.out.println(i);
                sum += i;
                num++;
            }
            //④ Iterative condition
            i++;
        } while (i <= 100); //② Cycle condition
        System.out.println("Sum of all even numbers:" + sum);
        System.out.println("Number of all even numbers:" + num);
    }
}

d) Comprehensive examples of circular sentences

Example: read an uncertain number of integers from the keyboard, judge the number of positive and negative numbers, and enter 0 to end the program
be careful:

  1. The simplest "infinite" loop format: while(true) and for(; 😉 , The reason for the existence of an infinite loop is that you do not know how many times the loop exists. You need to control the end of the loop according to some conditions inside the loop body.
  2. There are 2 ways to end the cycle
  • The loop condition part returns false
  • In the circulation body, execute break
import java.util.Scanner;
public class Day05_ForWhileTest {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int zhengshu = 0;
        int fushu = 0;

        //Loop with while
        while (true) {
            System.out.println("Please enter a number:");
            int number = scan.nextInt();
            if (number > 0) {
                zhengshu++;
            } else if (number < 0) {
                fushu++;
            } else {
                break;
            }
        }

//        //Loop with for
//        for (; ; ) {
//            System.out.println("please enter a number:");
//            int number = scan.nextInt();
//            if (number > 0) {
//                zhengshu++;
//            } else if (number < 0) {
//                fushu++;
//            } else {
//                break;
//            }
//        }

        System.out.println("Integer number is:" + zhengshu);
        System.out.println("The number of negative numbers is:" + fushu);
    }

}

e) Use of nested loops

  1. Nested loop: A nested loop is formed by declaring one loop structure A in the loop body of another loop structure B
  • Outer circulation: circulation structure B
  • Inner circulation: circulation structure A
  1. explain:
  • The memory loop structure is traversed once, which is only equivalent to the execution of the loop body of the outer loop once
  • Assuming that the outer loop needs to be executed m times and the inner loop needs to be executed n times, the loop body of the inner loop has been executed m * n times in total
  1. Skill: the outer loop controls the number of rows and the inner loop controls the number of columns
public class Day05_ForForTest {
    public static void main(String[] args) {
        /*
        Output:
        *
        **
        ***
        ****
        *****
         */
        for (int i = 1; i <= 5; i++) { //Number of control rows
            for (int j = 1; j <= i; j++) { //Number of control columns
                System.out.print("*");
            }
            System.out.println();
        }

        /*
        Output:
        *****
        ****
        ***
        **
        *
         */
        for (int i = 1; i <= 5; i++) { //Number of control rows
            for (int j = 5; j >= i; j--) { //Number of control columns
            // for (int j = 1; j <= 6 - i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Example 1: using nested loop to realize a 99 multiplication table

public class Day05_ForForTest {
    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();
        }
    }
}

Example 2: output all prime numbers within 100
Method before optimization

public class Day05_ForForTest {
    public static void main(String[] args) {
    long start = System.currentTimeMillis(); //Gets the number of milliseconds of the current time
        for (int i = 2; i <= 100; i++) {
            boolean flag = true;
            for (int j = 2; j <= i - 1; j++) {
                if (i % j == 0) {
                    flag = false;
                }
            }
            if (flag == true) {
                System.out.println(i);
            }
        }
        long end = System.currentTimeMillis(); //Gets the number of milliseconds of the end time
        System.out.println("The time taken is:" + (end - start));
    }
}
  • Optimization 1: add break to the calculation of non prime numbers
  • Optimization 2: calculate whether n is a prime number. It is not necessary to calculate whether there is a factor of N in all numbers in [2, n-1], but just calculate whether there is a factor of N in [2, sqrt(n)]
public class Day05_ForForTest {
    public static void main(String[] args) {
    long start = System.currentTimeMillis(); //Gets the number of milliseconds of the current time
        for (int i = 2; i <= 100; i++) {
            boolean flag = true;
            //Optimization 2: it is also effective for prime numbers and natural numbers
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    flag = false;
                    // Optimization 1: only valid for non prime natural numbers
                    break;
                }
            }
            if (flag == true) {
                System.out.println(i);
            }
        }
        long end = System.currentTimeMillis(); //Gets the number of milliseconds of the end time
        System.out.println("The time taken is:" + (end - start));
    }
}
  • Use continue with label
public class Day05_ForForTest {
    public static void main(String[] args) {
    long start = System.currentTimeMillis(); //Gets the number of milliseconds of the current time
        label:
        for (int i = 2; i <= 100; i++) {
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    continue label;//End the current cycle of the one rub cycle structure of the specified label
                }
            }
            System.out.println(i);
        }
        long end = System.currentTimeMillis(); //Gets the number of milliseconds of the end time
        System.out.println("The time taken is:" + (end - start));
    }
}

3. break and continue keywords

1) break and continue comparison
Scope of use Functions used in the loop (different points) Same point
break Switch case and loop structure End current cycle (entire cycle) Cannot declare execution statement after keyword
continue Cyclic structure End the current cycle and directly enter the next cycle Cannot declare execution statement after keyword
2) Tagged break and continue
  • In nested loops, break and continue take effect by default for the nearest level of loop containing this keyword. However, you can make it effective for the cycle of the specified layer by labeling.
public class Day05_ForForTest {
    public static void main(String[] args) {
        label:
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= 10; j++) {
                if (j % 4 == 0) {
                    //break label; // Ends the loop structure of the specified label
                    continue label; //End the current cycle of the one rub cycle structure of the specified label
                }
                System.out.print(j);
            }
        }
    }
}

Topics: Java