Learn JAVA regular expression packing class automatic packing / automatic unpacking BigDecimal

1 regular expression Regex

1.1 general

Correct string format rules.
It is often used to judge whether the content entered by the user meets the format requirements. Note that it is strictly case sensitive.

1.2 common syntax

1.3 String provides methods to support regular expressions

Matches: can the current string match a regular expression
Replaceall (regular, substring): replaces a substring
Split (regular): split strings

1.4 exercise: test the ID number.

Create package: CN tedu. api
Create class: testregex java

package cn.tedu.api;

import java.util.Scanner;
/*This class is used for regular expression introductory cases*/
//Requirement: receiving the ID number entered by the user and exporting the result of the judgement.
public class TestRegex {
    public static void main(String[] args) {
        //1. Edit regular expressions
        //The rule of ID number is 18, the first 17 are numbers, eighteenth may be numbers, or X.
        //String regex = "[0-9]{17}[0-9X]";
        /*A single \ has a special meaning in Java. It represents an escape symbol and is not considered a slash
         * So if you want to represent a slash, you need to precede it with an escape\
         * That is, \ \ is expressed as a simple slash
         * \t -- Tab \ rreturn \ nline break*/
        String regex = "\\d{17}[0-9X]";

        //2. define variables to receive user ID number:
        String input;

        //3. Judge whether the data entered by the user conforms to the regular expression. If it is incorrect, continue to enter
        do {
            System.out.println("Please input your ID number:");
            input = new Scanner(System.in).nextLine();
            if (input.matches(regex)) {//If the ID number is correct
                System.out.println("congratulations! Correct input!");
                return;//End this method
            }
        } while (!input.matches(regex));//Continue typing as long as it does not conform to the regular expression
    }
}

 

2 packaging

Package the basic types to provide more perfect functions.
The basic type has no function, just a variable and record value, while the wrapper class can have more functions

2.1 correspondence with basic types

2.2 Number

The abstract parent of the digital wrapper class.
Provides various ways to obtain values.

 

2.3 Integer


create object
Method 1: new Integer(5);
Method 2: integer valueOf(5);
The Integer class contains 256 Integer cache objects, ranging from - 128 to 127
When valueOf() is used, if the value is within the specified range, the cache object will be accessed directly without creating a new one; If you specify a value outside the range, create a new object directly.

Common methods
static int parseInt(String s) parses string parameters as signed decimal integers

2.4 exercise: Integer of Number


Create package: CN tedu. api
Create class: testnumber java

package cn.tedu.api;
/*This class is used to test packaging*/
public class TestNumber {
    //1. When defining member variables, pay attention to setting them to static, because static can only call static
    static Integer i0;
    public static void main(String[] args) {
        //2. Print the default value of Integer for testing
        System.out.println(i0);//The default value is null

        //3. Create an object of Integer type corresponding to int type -- Method 1
        Integer i1 = new Integer(5);
        Integer i11 = new Integer(5);
        System.out.println( i1 == i11 );//false, = = for reference types, address values are compared

        //4. Create an object of Integer type corresponding to int type -- Method 2
        /*Integer There is an efficient effect. The data are: (- 128 ~ 127)
        * Within this range, the same data will only be saved once, and subsequent saving will use the previously saved data*/
        Integer i2 = Integer.valueOf(127);
        Integer i3 = Integer.valueOf(127);
        System.out.println(i1 == i2);//false
        System.out.println(i2 == i3);//true
        //Three conditions for high efficiency are met: Integer valueOf() -128~127
        Integer i4 = Integer.valueOf(300);
        Integer i5 = Integer.valueOf(300);
        System.out.println(i4 == i5);//false

    }
}


 

2.5 Double


create object
new Double(3.14)
Double.valueOf(3.14) / / no difference from new
common method
Double.parseDouble();

2.5 exercise: Double of Number
Create package: CN tedu. api
Create class: testnumber java

package cn.tedu.api;
/*This class is used to test wrapper classes of basic types*/
public class TestNumber {
    public static void main(String[] args) {
        //1. How to create int wrapper class Integer object 1
        Integer i1 = new Integer(100);
        Integer i11 = new Integer(100);
        System.out.println(i1 == i11);//False and new twice. They are two different objects with different address values

        //2. How to create int wrapper class Integer object 2
        /*Integer There is an efficient effect, but three conditions must be met:
        * 1.Is an Integer type
        * 2.Create using valueOf()
        * 3.The data is in the range of - 128 ~ 127
        * If the above conditions are met, the same data will only be saved once, and the subsequent reuse is the previously saved data*/
        Integer i2 = Integer.valueOf(100);
        Integer i22 = Integer.valueOf(100);
        System.out.println(i2 == i22);//true

        Integer i3 = Integer.valueOf(300);
        Integer i33 = Integer.valueOf(300);
        System.out.println(i3 == i33);//false out of the efficient data range - 128 ~ 127

        //3. How to create double wrapper class double object 1
        Double d1 = new Double(3.14);
        Double d11 = new Double(3.14);
        System.out.println(d1 == d11);//false, create two different objects with different address values

        //4. How to create double wrapper class double object 2
        /*Only Integer has efficient effect, and Double does not*/
        Double d2 = Double.valueOf(3.14);
        Double d22 = Double.valueOf(3.14);
        System.out.println(d1 == d2);//false
        System.out.println(d2 == d22);

        //5. Common test methods
        //The function of this method is to convert the incoming String type data into int
        /*You can use all the resources of this class according to the type of object
        i1 Is an object of type Integer, so you can use parseInt() to convert data of type String to type int
        d1 It is an object of double type, so you can use parseDouble() to convert the data of String type to double type*/
        System.out.println(i1.parseInt("800")+8);//808->int+int
        System.out.println(d1.parseDouble("2.2")+3.1);//5.300000000000001->double+double
    }
}

3 automatic packing and unpacking


3.1 general


Automatic packing: the process of packing basic types into corresponding packing types
Integer a = 5;//a is the reference type and refers to the address of the wrapper object.
The compiler completes the automatic boxing of objects: integer a = integer valueOf(5);

Automatic unpacking: automatically changes from the value of package type to the value of basic type
int i = a;//a is the packing type now. It is impossible to assign a value to the variable. You need to take out 5.
The compiler will complete automatic unpacking: int i = a.intValue();

3.2 exercise: automatic packing and automatic unpacking test


Create package: CN tedu. api
Create class: testbox java

package cn.tedu.api;
/*This class is used to test automatic packing and unpacking*/
public class TestBox {
    public static void main(String[] args) {
        //1. Data defining package type
        //Review: there are two ways to create packaging types in the past
        Integer i1 = new Integer(127);
        Integer i2 = Integer.valueOf(127);
        //2. Current approach:
        /*1.Auto boxing: the compiler will automatically wrap the basic type int 5 into the wrapper type Integer
        * Then give it to i3 to save, and automatically pack the underlying code integer valueOf(5);
        * valueOf()Direction of: int -- > integer*/
        Integer i3 = 5;//No error will be reported. This phenomenon is automatic packing
        /*2.Automatic unpacking: the compiler will automatically remove the "box" of i1 of packaging type and change it back to basic type data 127
        * Then give it to i4 to save. The code at the bottom of automatic unpacking: I1 intValue();
        * intValue()Direction of: integer - > int
        * */
        int i4 = i1;//No error will be reported. This phenomenon is automatic unpacking
    }
}

4.1 creating objects


Mode 1:
BigDecimal(double val)
Convert double to BigDecimal, which is the decimal representation of binary floating-point value of double. There is a pit!
Mode 2:
BigDecimal(String val)
Converts the form of a String of type String to BigDecimal

4.2 common methods

Add(BigDecimal bd): add
Subtract(BigDecimal bd): perform subtraction
Multiply(BigDecimal bd): perform multiplication
Divide(BigDecimal bd): perform a division operation. Exceptions will be thrown if the division is not complete
Divide(BigDecimal bd, reserved digits, rounding method): used when division is not complete
Setscale (reserved digits, rounding method): the same as above
pow(int n): find the power of data

 

4.3 exercise: Common test methods

Create package: CN tedu. bigdecimal
Create class: testbigdecimal java
Requirement: receive two decimals entered by the user for calculation

package cn.tedu.api;

import java.math.BigDecimal;
import java.util.Scanner;

public class TestBigDecimal {
    public static void main(String[] args) {
        //f1();// The use of ordinary + - * / four arithmetic operations exposes the imprecision of floating-point arithmetic
        f2();//BigDecimal is used to solve the imprecise problem of floating-point operation
    }

    private static void f2() {
        //1. Prompt and receive two decimals entered by the user
        System.out.println("Please enter the two decimals you want to calculate:");
        double a = new Scanner(System.in).nextDouble();
        double b = new Scanner(System.in).nextDouble();
        //2. Create a tool class object and give the basic types A and b to the tool class object BigDecimal to save
        /*1.It's best not to use double as the parameter of the constructor, otherwise there will be imprecision and pit!!!*/
        /*2.It is best to use an overloaded constructor whose parameter type is String
        * double Turn to String and spell an empty String directly*/
        BigDecimal bd1 = new BigDecimal(a+"");
        BigDecimal bd2 = new BigDecimal(b+"");

        //3. Call its method through BigDecimal object to realize accurate operation
        //3.1 define the reference type variable of BigDecimal type to save the results
        BigDecimal bd3;
        //3.2 Add(BigDecimal bd): add
        bd3 = bd1.add(bd2);
        System.out.println(bd3);
        //3.3 Subtract(BigDecimal bd): perform subtraction
        bd3 = bd1.subtract(bd2);
        System.out.println(bd3);
        //3.4 Multiply(BigDecimal bd): perform multiplication
        bd3 = bd1.multiply(bd2);
        System.out.println(bd3);
        //3.5 Divide(BigDecimal bd): perform a division operation, and throw an exception if the division is not complete
        /*3.In the division operation, an exception ArithmeticException will be thrown when the division is not complete*/
        //Scheme 1: (except that there are problems when it is not enough)
        //bd3 = bd1.divide(bd2);
        /*divide(m,n,o)
        m Is the object to be divided by, n refers to the number of digits to be retained, and o refers to the rounding method (such as rounding)*/
        //Scheme II:
        bd3 = bd1.divide(bd2,3,BigDecimal.ROUND_HALF_UP);
        System.out.println(bd3);

    }

    private static void f1() {
        //1. Prompt and receive two decimals entered by the user
        System.out.println("Please enter the two decimals you want to calculate:");
        double a = new Scanner(System.in).nextDouble();
        double b = new Scanner(System.in).nextDouble();

        //2. Do calculations
        System.out.println(a + b);//imprecise
        System.out.println(a - b);//imprecise
        System.out.println(a * b);//imprecise
        System.out.println(a / b);//imprecise
    }
}

Here, the first API lesson is over. Congratulations on passing another level~

5 expansion

Rounding method analysis
ROUND_HALF_UP is rounded, for example: 4.4, the result is 4; 4.5 the result is 5
ROUND_HALF_DOWN is rounded off and not rounded off. For example, 4.5 results in 4; 4.6 the result is 5
ROUND_HALF_EVEN fair rounding (commonly used by banks)
For example, between 5 and 6, close to 5 is discarded as 5, close to 6 is carried as 6, if it is 5.5, find an even number and become 6
ROUND_UP carries directly, not counting 0.1 or 0.9
ROUND_DOWN is discarded directly, not counting 0.1 or 0.9
ROUND_ Ceiling is rounded up to the greater of the actual value
In the direction of positive infinity, if round is a positive number, the behavior is the same as round_ Same as up, if it is negative, the behavior is the same as round_down like
ROUND_ Floor is rounded down to take the small value of the actual value
In the negative infinite direction, if round is a positive number, the behavior is the same as round_ Like down, if it is negative, the behavior is the same as round_ Same as up

Keywords: Java regex

Added by oocuz on Sat, 01 Jan 2022 22:01:50 +0200