JAVA foundation - API exception handling, take a good look and learn

Posted by luminous on Fri, 19 Nov 2021 17:36:42 +0100

JAVA----API

1, API

1. Basic use of scanner

API Explanation:
	The full name is application programming interface(Application Programming Interface), Originally meant to mean JDK Various classes and interfaces provided

For example: Scanner Get string
	public String nextLine();	Get the string entered by the user and get the whole line of data.
	public String nextInt();	Get data of integer type
	public String next();		Get the string entered by the user, but only the content before the space
  • Code demonstration
//Automatic package Guide
import java.util.Scanner;

/*
    Show me how Scanner gets strings
 */
public class Demo01 {
    public static void main(String[] args) {
        //Create Scanner object
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the name of the person you love: ");

        // Receive keyboard input results
        String str = scanner.nextLine();

        // You can only receive content before a space
        //String str = sc.next();
        //Print
        System.out.println(str);
    }
}

2.Scanner tips

Scanner Details:
	Problem Description:
		First use nextInt() Receive integers, and then nextLine() Received string, found that the string cannot be received.
	Causes:
		1. nextInt() , nextLine() Both method end tags are \r\n
		2. nextInt() Method only receives the integer entered by the user, not the integer \r\n
		3. It's a legacy \r\n Can only be nextLine() Identify, cause nextLine() Method ends directly.

	Solution:
		1. All are received in a string, and then the integer in the form of string is transformed into the corresponding integer.  ---->[Master: This is the actual development practice]
			int num = Integer.parseInt("123");
				
		2. again new One Scanner Object.
		3. Call again newLine() method.
		4. adopt next() Method implementation.
		5. Try first nextLine(), then nextInt() It can also be solved.	
  • Basic operation:
package demo01_scanner;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        // ==============[problem code]==============
    /*
        //Create Scanner object
        Scanner sc = new Scanner(System.in);

        // Receive keyboard input results
        System.out.println("Please enter an integer: ");
        // Receive input integer
        int num = sc.nextInt();
        // Print
        System.out.println("num " + num);   //520

        //Then call nextLine() to receive the string
        System.out.println("Please enter the string "");
        String str = sc.nextLine();
        System.out.println(str);
        //Problem Description: after the number is input, the string cannot be input and the operation will be automatically exited. Reason \ r\n

     */

        System.out.println("----------------[Gorgeous split line]----------------");

        //=================[solution]=================
        // 1 are received in strings, and then the integers in the form of strings are converted into corresponding integers ------ [Master, practice of actual development]
        // int num = Integer.parseInt("123");

        Scanner sc = new Scanner(System.in);

        // Receive keyboard input results
        System.out.println("Please enter an integer: ");

        // Receive integer
        String str_num = sc.nextLine();
        //Integer the string "123" = = = = 123
        // Integer. ParseInt ("123") = = > 123 forced rotation
        int num = Integer.parseInt(str_num);

        // print contents
        System.out.println("num " + num);

        //Receive the string with nextLine()
        System.out.println("Please enter a string: ");

        String str = sc.nextLine();
        System.out.println(str);

    }
}

3. toString and equals methods of object class

Object Class introduction: 'It is the parent of all classes, and all classes inherit directly or indirectly from Object class'
	Construction method:
		public Object();

	Member method:
		public String toString()
			
			Returns the string representation of the object.
			Author: the format is: full class name,@Flag, the unsigned hexadecimal form of the hash code of the object. ===>Address of the object
	Actual development: meaningless. In actual development, subclasses will rewrite the method and print the attribute values of the object instead.

	How to rewrite it? Shortcut key generation.

	public boolean equals(Object obj);
		Author: compare whether two objects are equal(That is: is it the same object),The default comparison is whether the address values are equal, which is meaningless
		Actual development: subclasses will override this method to compare whether the attribute values of each object are equal.
		give an example:
			stu1.name == stu2.name
            stu1.age == stu2.age
            stu1 and stu2 The address must be different new Twice
            If each attribute is equal, it can be considered the same object

Details('memory'):
	1. In actual development, we believe that if multiple objects of the same class have the same attribute value, they are the same object, that is:
		Student s1 = new Student("Ma Jiayu" ,23);
		Student s2 = new Student("Ma Jiayu" ,23);
		In the actual development of the above two objects, we will also think that they are the same object.
	2. The output statement prints the object directly. By default, the output statement of the object is called toString()method.
  • code
public class Demo01 {
    public static void main(String[] args) {
        //1. Demonstrate toString method
        Student student = new Student();

        //Not overridden: toString method
        //Author: the format is: full class name, @ tag, and the unsigned hexadecimal form of the hash code of the object. = = > the address of the object
        //Rewriting toString method: actual development: meaningless. In actual development, subclasses will rewrite this method and print: the attribute values of the object
        System.out.println(student);
        System.out.println(student.toString());

        //Demonstrate the equals method
        Student stu1 = new Student("Ma Jiayu" ,23);
        Student stu2 = new Student("Ma Jiayu" ,23);
        //The equals method has not been overridden
        //Author: compare whether two objects are equal (i.e. whether they are the same object). The default comparison is whether the address values are equal. It is meaningless and false

        //equals has been overridden
        //Actual development: subclasses will override this method to compare whether the attribute values of each object are equal
        boolean flag = stu1.equals(stu2);
        System.out.println(flag); //true
    }
}

4. Detailed explanation of string comparison

String Class introduction:
	He is java.lang The class under the package can be used directly without leading the package. It represents all strings, and each string is its object.
		String s1 = new String("abc");
		String s1 = "abc";  //new free sugar

				Member method:
		public boolean equals(Object obj);
			This is String Rewritten Object#The equals() method compares whether the contents of the string are the same and is case sensitive.
			Note: it is no longer to compare whether the addresses are consistent, but to compare whether the addresses are consistent: ===Comparison operator
		public boolean equalsIgnoreCase(String s)
			This is String Unique method to compare whether the contents of strings are the same, case insensitive.

	Requirements:
		Define character array chs,The initialization value is:'a' ,'b' ,'c' ,These three characters.
		Package them into s1 ,s2 These two string objects
		Directly through "" To create two string objects s3 and s4 
		adopt == Judge separately s1 and s2 , s3 and s4 Whether it is the same.
		adopt equals() Judge separately s1 and s2 , s3 and s4 Whether it is the same.
		adopt equalsIgnoreCase() Judgment string abc and ABC Is it the same

	Details: (memory)
		1. == Role of:
			Compare basic types: compare values.     ten == 20  Comparison value
			Compare reference types: address values are compared     s1 == s2  Compare address values
		2. String# equals() is case sensitive. equalsIgnoreCase() ignores case
  • code
package demo02_object;

/**
 * Requirements:
 *  Define the character array chs with initialization values of 'a', 'b', 'c'
 *  Encapsulate them into s1 and s2 string objects respectively
 *  Create two string objects s3 and s4 directly through ''
 *  Determine whether s1 and S2, s1 and S3, S3 and s4 are the same through = = respectively
 *  Judge whether s1 and s2, s1 and s3, s3 and s4 are the same through equals()
 *  Judge whether the strings ABC and ABC are the same through equalsIgnoreCase()
 */
public class Demo02 {
    public static void main(String[] args) {
        //Define character array chs initialization values as: 'a', 'b', 'c', these three characters
        char[] chs = {'a' ,'b' ,'c'};
        // Shortcut key: alt + shift + cursor to select multiple lines
        // Encapsulate them into S1 and S2 string objects respectively
        String s1 = new String(chs);
        String s2 = new String(chs);

        //Create two string objects s3 and s4 directly through ''
        String s3 = "abc";
        String s4 = "abc";

        // Judge whether s1 and s2, s1 and s3, s3 and s4 are the same by = = respectively
        // TODO: Note: it is no longer to compare whether the addresses are consistent, but to compare whether the addresses are consistent: = = comparison operator
        System.out.println(s1 == s2); // false because new is created twice, not in the same space
        System.out.println(s1 == s3); // false two different objects have different addresses
        System.out.println(s3 == s4); // true there is only one space in memory
        System.out.println("----------------[Gorgeous split line]----------------");
        // Judge whether s1 and s2, s1 and s3, s3 and s4 are the same through equals()
        // TODO:equals() judge whether the content is consistent
        System.out.println(s1.equals(s2)); // true compares the content and the content is consistent
        System.out.println(s1.equals(s3)); // true compares the content and the content is consistent
        System.out.println(s3.equals(s4)); // true compares the content and the content is consistent

        System.out.println("----------------[Gorgeous split line]----------------");
        // Judge whether the strings ABC and ABC are the same through equalsIgnoreCase(). Ignore case
        System.out.println("abc".equals("ABC")); // false equals is case sensitive
        System.out.println("abc".equalsIgnoreCase("ABC")); // true is case insensitive\
    }
}

5. Simulated Login

  • thinking
1. Define variables and record account and password
2. establish Scanner object
3. Because there are only three opportunities to use it for loop
4. Prompt the user to enter the account and password and receive it
5. Judging whether the entered account and password are correct is equivalent to successfully exiting the program
6. If you do not correctly judge whether there are remaining login times, continue to lock the account
  • code
package demo02_object;

import java.util.Scanner;

/*
    Case: simulated landing

    Requirements:
       Simulate user login, only 3 opportunities are given, and "welcome, * * *" will be prompted if login is successful
       If login fails, judge whether there is still login opportunity. If yes, prompt the remaining login times. If not, prompt "your account has been locked"
       Assume that the initialization account and password are respectively "wisdom podcast" and "dark horse programmer"

     // 1.Define variables, record account and password "wisdom podcast" and "dark horse programmer"
     // 2.Create Scanner object
     // 3.Because there are only three opportunities, use the for loop
     // 4.Prompt the user to enter the account and password and receive it
     // 5.Judge whether the entered account and password are normal and correct. If the login is successful, you will be prompted with "welcome, * * *"
     // 6.If it is incorrect, judge the remaining login times, prompt the remaining login times if any, continue, and prompt "your account has been locked" if No

 */
public class Demo03_Login {
    public static void main(String[] args) {
        // 1. Define variables and record the account and password "wisdom podcast" and "dark horse programmer"
        String username = "Ma Jiayu";
        String password = "Hello";

        // 2. Create scanner object
        Scanner sc = new Scanner(System.in);

        // 3. Because there are only 3 opportunities to use the for loop
        // Shortcut key fori
        for (int i = 0; i < 3; i++) {
            System.out.println("Please enter your password: ");
            String usern = sc.nextLine();
            System.out.println("Please enter your password: ");
            String pass = sc.nextLine();

            // 5. Judge whether the entered account and password are normal and correct. If the login is successful, you will be prompted with "welcome, * * *"
            // Judge equal values: equals method
            if (usern.equals(username) && pass.equals(password)) {
                System.out.println("Welcome to login: " + usern);

                //Jump out of loop
                break;
            }else {
                // 6. If it is incorrect, judge the remaining login times, prompt the remaining login times if any, continue, and prompt "your account has been locked" if No
                // Remaining times??? Formula: 2 - i = number of times
                /*if((2 - i) > 0){
                    System.out.println("You still have "+ (2-i) +" opportunities ") due to input errors;
                }else{
                    System.out.println("The maximum number of errors has been reached, and the account is locked. Please contact the administrator ");
                }*/

                // Optimization: ternary operators
                System.out.println(2 - i > 0 ? "Input error, you still have" + (2 - i) + "Second chance" : "The maximum number of errors has been reached. The account is locked. Please contact the administrator");
            }
        }
    }
}

6. Traversal string

  • Idea:
1. Prompt the user to enter a string and receive it
2. Traversal string
  • code
package demo02_object;

import java.util.Arrays;
import java.util.Scanner;

/*
    Case: traversal string

    Requirements:
        Keyboard input a string, use the program to traverse and print the string on the console

    Member methods in the String class involved:
        public char charAt(int index);      Get the corresponding characters according to the index
        public int length();                Gets the length of the string
        public char[] toCharArray();        Converts a string to its corresponding character array
 */
public class Demo03_Iter {
    public static void main(String[] args) {
        // 1. Prompt the user to enter a string and receive it
        // Quick package guide shortcut key alt + ENTER
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string: ");
        //"abcde"
        String s = sc.nextLine();
        // 2. Traversal string
        // Scheme 1: for loop traversal
        for (int i = 0; i < s.length(); i++) {
            // i is the subscript
            char c = s.charAt(i);
            System.out.println(c);
        }
        System.out.println("----------------[Gorgeous split line]----------------");

        //Scheme 2 toCharArray() converts a string into a character array
        // "abcde" ==>['a' ,'b' ,'c' ,'d' ,'e']
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char ch = chars[i];
            System.out.println(ch);
        }
        System.out.println("----------------[Gorgeous split line]----------------");

        // Actual development
        //s.toCharArray() is converted to a string array
        // Arrays.toString() prints each element of the array
        System.out.println(Arrays.toString(s.toCharArray()));
    }
}

7. Count the number of characters of each type

  • thinking
Define statistical variables to record results
 Enter a string on the keyboard and receive it
 Traverse the string to get each character
 Judge which category the character belongs to, and get the counter corresponding to the category ++
  • code
package demo04_exercise;

import java.util.Scanner;

/*
    Case: count the times of no class characters and print the results
    Requirements:
        Enter a string on the keyboard and count the number of occurrences of uppercase string, lowercase alphanumeric characters in the string
        Note: other characters, such as @!, are not considered/ etc.
 */
public class Demo03 {
    public static void main(String[] args) {
        // Define statistical variables to record results
        int smallCount = 0, bigCount = 0, numberCount = 0;
        // Keyboard input a string and receive abc12ABCD@#$
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string: ");
        String s = sc.nextLine();

        //3. Traverse the string to get each character
        char[] chs = s.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            //ch is every character in the string
            char ch = chs[i];  //"a" ,'B'
            // The counter that determines which category the character belongs to and to whom it belongs++
            if (ch >= 'a' && ch <= 'z')
                smallCount ++;
            else if (ch >= 'A' && ch <= 'Z')
                bigCount++;
            else if (ch >= 'O' && ch <= '9')
                numberCount++;
        }
        // Print results
        System.out.println("Lowercase character: " + smallCount);
        System.out.println("Uppercase character: " + bigCount);
        System.out.println("Numeric character: " + numberCount);
    }
}

8. Basic use of StringBuilder

  • thinking
StringBuilder Introduction:
	It represents a string buffer class whose content is variable

Construction method:
	public StringBulider();
	public StringBulider(String s);
	This construction method can be understood as being used to realize: converting a string into a corresponding string StringBuilder Object.
	String character string  ==> StringBulider String buffer class

Member method:
	public String toString(); 	rewrite object#toString(), print object content
	public String reverse(String); Invert the string to return itself
	public boolean append(Object obj); Add element to return to itself
  • code
package demo08_StringBuilder;
/*
    //StringBuilder Introduction:
           It represents a string buffer class whose content is variable

    //Construction method:
        public StringBuilder();
        public StringBuilder(String s);
        This construction method can be understood as being used to convert a string into a corresponding StringBuilder object
        String String class = = > StringBuilder string buffer class

    //Member method:
          public String toString();           Override Object#toString() to print the content of the object
          public String reverse(String);      Inverts the string and returns itself
          public boolean append(Object obj);  Add an element and return to itself
 */

/**
 * Demonstrate getting started with StringBuilder
 * Requirements:
 *     Create a StringBuilder object in the above two ways
 *     Print the above two created objects directly on the console and observe the results
 */
public class Demo01 {
    public static void main(String[] args) {
        // Scheme 1: create StringBuilder object with null parameter construction
        StringBuilder sb1 = new StringBuilder();
        // Add the element and return the StringBuilder object
        StringBuilder sb2 = sb1.append("abc");
        StringBuilder sb3 = sb1.append("123");

        System.out.println(sb1);
        System.out.println(sb2);
        System.out.println(sb3);

        System.out.println("----------------[Gorgeous split line]----------------");

        System.out.println(sb1 == sb2); //Same address true
        System.out.println(sb1 == sb3); //Same address true
        System.out.println(sb2 == sb3); //Same address true

        //Conclusion:
        // 1. Because you only use new to create sb1 objects at the beginning
        // 2.sb2 and sb3 are variables pointing to the same memory area

        System.out.println("----------------[Gorgeous split line]----------------");
        //Scenario 2: create a StringBuilder object using string initialization
        // Essence: String = = StringBuilder
        StringBuilder sb4 = new StringBuilder("james");
        System.out.println(sb4);
    }
}

9. Conversion between StringBuilder and string

  • Question: why do types convert to each other?
    • Answer: when a class A wants to use the function of the class B, we can try to convert the class A object into a B object, so that we can call the class B method and then return to class A after the call is completed.
package demo08_StringBuilder;
/*
    Case: demonstrate the conversion between String and StringBuilder

    String -> StringBuilder:
        Through the construction method of StringBuilder, i.e. public StringBuilder(String s);

    StringBuilder -> String:
        Use the StringBuilder#toString() method, that is, public String toString();
 */
public class Demo02 {
    public static void main(String[] args) {
        // 1.String -> StringBuilder;
        String name = "Ma Jiayu";
        StringBuilder sb1 = new StringBuilder(name);
        System.out.println(sb1);
        System.out.println("----------------[Gorgeous split line]----------------");

        // 2.StringBuilder -> String
        String new_str = sb1.toString();
        System.out.println(new_str);
    }
}

10. Splice array elements

  • Chained call:
    • If the return value of a method is an object, you can continue to call the method of the object directly through the syntax
  • Actual development writing method
  • Arrays.toSring(arr)
  • code
package demo05_StringBuilder;

import java.util.Arrays;

/*
    Splice array elements
    Requirements:
        Define the method arrayToString() to splice the elements of the int array into a string according to the specified format and return
        The above method is invoked in the main method.
        For example: array int[] arr = {1,2,3}, after splicing, the result is: [1,2,3]
 */
public class Demo03 {
    public static void main(String[] args) {
        //1. Define array
        int[] arr = {1,2,3};

        //Actual development method:
        System.out.println(Arrays.toString(arr));

        System.out.println("----------------[Gorgeous split line]----------------");

        //Call the custom arrayTostring method
        String s = arrayToString(arr);
        System.out.println(s);
    }

    /**
     * Convert array to string
     * @param arr   int Type array
     * @return      character string
     * For example, if the array is int[] arr = {1,2,3}, the result after splicing is: [1,2,3]
     */
    public static String arrayToString(int[] arr) {
        // 1. Judgment of non empty array
        if (arr == null || arr.length == 0) {
            // Returns an empty array
            return "[]";
        }

        //2. Define the object of StringBuilder class and accept cached string data
        StringBuilder sb = new StringBuilder("[");

        // Traverse the array to complete data splicing
        // Array traversal shortcut itar
        for (int i = 0; i < arr.length; i++) {
            //arr = {1,2,3} after splicing, the result is: [1,2,3]
            // If we don't get to the last element, we add the elements and commas of the array
            if (i != (arr.length - 1)) {
                //Add elements and commas to the array
                // Chain call: if the return value of a method is an object of this class, you can continue to call other methods of this object later
                sb.append(arr[i]).append(",");
            } else {
                // If we go to the last element, we add the number element and "]"
                sb.append(arr[i]).append("]");
            }
        }
        // Converts a StringBuilder object to a string and returns
        return sb.toString();
    }
}

11.StringBuilder inverts strings

  • Chained call:
  • If the return value of a method is an object, you can directly call the method of the object through the syntax
  • code
package demo05_StringBuilder;

import java.util.Scanner;

/*
    Reverse string
    Requirements:
        Enter a string on the keyboard, then reverse its content and print it

    Idea: implemented by StringBuilder#reverse() method
        1. Put string - > StringBuilder
        2. Call StringBuilder#reverse() to reverse the content
        3. Put StringBuilder - > string
        4. Print results
 */
public class Demo04 {
    public static void main(String[] args) {
        // Input string
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string: ");
        String s = sc.nextLine();
        System.out.println("Before reversal: " + s);  //Before inversion: sdfslkdfjsldf
        System.out.println("----------------[Gorgeous split line]----------------");
        //1. Set String - StringBuilder
        StringBuilder sb = new StringBuilder(s);

        //2. Reverse the contents of StringBuilder#reverse()
        sb.reverse();

        //3. Set StringBuilder - String
        String new_str = sb.toString();
        //4. Print results
        System.out.println("After reversal: " + new_str);   //After reversal: fdlsjfdklsfds
        System.out.println("----------------[Gorgeous split line]----------------");

        //Scheme 2: chain call, one sentence of code
        String s1 = new StringBuilder(s).reverse().toString();
        System.out.println(s1);

    }
}

  • Data structure algorithm: bubble sort, quick sort, Hill sort, heap sort.......

12. Bubble sorting

  • Bubble sorting principle:
    • The adjacent elements are compared in pairs, and the larger ones go back, so that after the first round of comparison, the maximum value is led out by the maximum
  • code
package demo06_sort;

import java.util.Arrays;

/*
    Case: demonstrate bubble sorting
    Requirements:
        Known array int[] arr = {25, 69, 80, 57, 13}, please write code to align and sort in ascending order
        That is, after sorting, the result is: arr = {13, 25, 57, 69, 80};

    Core points:
        1. How many rounds are compared?
            arr.length - 1
        2. How many times per round?
            arr.length - 1 - i
        3. Who compared with whom?
            arr[j] And arr[j+1]

    Soul three questions:
        1. What does the - 1 of the outer loop mean?
            You don't need to compare with yourself in the last round to reduce the number of comparisons and improve performance
        2. What does the - 1 of the inner loop mean?
            Prevent index overruns
        3. What does the - i of the inner loop mean?
            Reduce the number of comparisons per round and improve performance
 */
public class Demo01_Sort {
    public static void main(String[] args) {
        //1. Define array
        int[] arr = {25,69,80,57,13};

        //2. Define outer cycle control: total number of rounds compared arr.length -1
        //Collapse shortcut ctrl +-
        for (int i = 0; i < arr.length - 1; i++) {// 0 1 2 3
            //3. Define the inner loop to control the times of each round of comparison arr.length -1 -i
            for (int j = 0; j < arr.length -1 - i; j++) {
                // 4. Pairwise comparison. If the previous value is larger than the latter value, exchange the elements with larger position = = "bubbling"
                //Previous value: arr[j]
                //The last value: arr[j + 1]
                if (arr[j] > arr[j + 1]) {
                    /*
                        a And b exchange
                        temp Temporary variable record
                        int temp = a;
                        a = b;
                        b = temp;
                     */
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }

        // 5. Print results
        System.out.println(Arrays.toString(arr));
            //The results are: [13, 25, 57, 69, 80]
        /*for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }*/
    }
}

2, Arrays

1. Demonstrate the usage of Arrays tool class

  • Arrays tool class concept:
    • It is a tool class used to manipulate arrays, which defines a large number of methods to manipulate array elements, such as sorting, converting strings, etc.
  • Format:
Member methods involved:
	1. Sort the array in ascending order. The default is ascending order.
		public static void sort(int[] arr);
	2. Convert an array to its corresponding string representation, such as: int[] arr = [1,2,3]; --> "[1,2,3]"
		public static String toString(Array object);

Tool class:
	1. Members are static
	2. Construction method privatization
  • code:
package demo06_sort;

import java.util.Arrays;

public class Demo02_Array_Sort {
    public static void main(String[] args) {
        //1. Define array
        int[] arr = {25,69,80,57,13};

        //2. Sort the array
        Arrays.sort(arr);

        //3. Print array results
        System.out.println(Arrays.toString(arr));
    }
}

4, Packaging

1. Introduction to packaging

  • concept
Introduction to packaging
 Introduction to packaging:
	'	The so-called wrapper class refers to the reference type corresponding to the basic type.	'
	Correspondence:
		Basic type				Corresponding packaging class(reference type)
		byte					Byte
		short					Short
		char					Character
		int  					Integer
		long					Long
		float					Float
		double					Double
		boolean					Boolean

	Main purpose of learning packaging:
		'	String Type of data  ==transformation==>  The basic type corresponding to this wrapper class	'

	For example:
		Integer	It's used to put	"123" 	-> 123
		Double	It's used to put	"10.3" 	-> 10.3
		Boolean It's used to put "false" -> false
		..........

	Integer Class interpretation:
		summary:
			'	He is int Reference type corresponding to type(Packaging),Mainly applicable to"123" 	-> 123	'
		Construction method:
			public Integer(int i);			establish Integer Object, encapsulating: integers.
			public Integer(String s);		establish Integer Object, encapsulation: string, which must be a pure numeric string
		Member variable:
			public static final int MAX_VALUE;		int Type maximum.
			public static final int MIN_VALUE;		int Type minimum.
  • code
package demo04_exercise;
/*
    Case: introduction to packaging
 */
public class Demo01 {
    public static void main(String[] args) {
        // int type Max
        System.out.println(Integer.MAX_VALUE);

        //int type minimum
        System.out.println(Integer.MIN_VALUE);

        //Construction method
        //Create an Integer object to encapsulate: integers
        Integer il = new Integer(10);
        System.out.println(il);

        // Create an Integer object to encapsulate: string, which must be a pure numeric string
        Integer i1 = new Integer("123");
        System.out.println(i1);
    }
}

2. Conversion between int and String

  • Conversion between int and String
int and String How to convert between
	int ---> String: 
		String s = "" + 10;

	String ---> Int: 
		int num = Integer.parseInt("123");

Integer Method interpretation in class:
     public static int parseInt(String s);  Converts an integer in the form of a string to its corresponding int type.

Memory (details):
	All packaging classes have one parseXXX()Method to convert string data into data of the basic type corresponding to the type
	For example:
		int num = Integer.parseInt("123");
		double d = Double.parseDouble("10.3");
        boolean flag = Boolean.parseBoolean("true");		
  • code:
package demo07_interger;
/*
    int How to convert between and String
 */
public class Demo01 {
    public static void main(String[] args) {
        //Requirement: how to convert int and String to each other:

        //1. int -> String:
        String str = "" + 10;
        System.out.println(str);
        System.out.println("----------------[Gorgeous split line]----------------");

        //2.String -> Int
        String str_int = "520";
        int num  = Integer.parseInt(str_int);
        System.out.println(num);

        // infer other things from one fact
        /*
        Double.parseDouble("10.11");
        Float.parseFloat("11.11");
        Boolean.parseBoolean("true");
        */
    }
}

3. String element sorting

demand:
    Known string String s = "91 27 45 38 50";
    Please implement it in code. The final output is: "27, 38, 45, 50, 91"

Idea:
	1. hold String Converts a string to its corresponding string array.
			String[] arrstr = {"91", "27", "45", "38", "50"};
	2. hold String[]  -> int[]
            int[] arr = [91, 27, 45, 38, 50];
    3. yes int[]Sort.
            int[] arr = [27, 38, 45, 50, 91];
    4. Concatenate the last obtained array elements into a string of the corresponding format.
            "27, 38, 45, 50, 91"

Member methods involved:
	String Methods of members in class:
		public String[] split(String regex);	Cut the string according to the rules.
		public String substring(int start ,int end);  Intercept the string. The left package does not include the right package.
		public String replaceAll(String older ,String newStr); Replace string

	Integer Member methods in class:
		Convert string to int type
			parseInt();
			
	Arrays Member methods in class:
		Array sorting
			sort(),
			Print array
			toString()
  • code
package demo07_interger;

import java.util.Arrays;

/**
 * Case list: string element sorting
 * Known string String s = "91 27 45 38 50";
 * Please implement it in code. The final output is: "27, 38, 45, 50, 91"
 */
public class Demo02 {
    public static void main(String[] args) {
        String str = "91 27 45 38 50";
        //1. Convert the String to the corresponding String array
        //"91 27 45 38 50" ==>  String[] arrStr = {"91", "27", "45", "38", "50"}
        String[] arrstr = str.split(" ");

        //2. Convert String array String [] to int [] integer array
        //int[] arr = {91, 27, 45, 38, 50}
        int[] intArr = new int[arrstr.length];
        // Traverse the string array, convert each string into an integer, and then load it into the int [] integer array
        for (int i = 0; i < arrstr.length; i++) {
            String str1 = arrstr[i];
            // Converts each string to an integer
            intArr[i] = Integer.parseInt(str1);
        }
        //3.int [] sort integer arrays in ascending order
        Arrays.sort(intArr);

        //4. The sorted int [] integer array is spliced into a string
        // [27, 38, 45, 50, 91] = = > target: "27, 38, 45, 50, 91"
        String s11 = Arrays.toString(intArr);
        // String interception
        //String s12 = s11.substring(1, s11.length() - 1);
        // String replacement
        // Parameter 1: old string parameter 2: new string note: \ \ translation
        String s12 = s11.replaceAll("\\[","").replaceAll("]","");
        //"27, 38, 45, 50, 91"
        System.out.println(s12);

    }
}

4. Automatic disassembly and assembly box (characteristics of JDK1.5)

  • code
package demo07_interger;

import com.sun.tools.corba.se.idl.InterfaceGen;

/*
    Case: demonstration of automatic disassembly box (JDK1.5 features)

    Packing: int - > integer, i.e. basic type - > Packing class
    Unpacking: integer - > int, i.e. packing class - > basic type
 */
public class Demo03 {
    public static void main(String[] args) {
        // 1. Packing
        // The writing method before JDK1.5: int - > integer,
        Integer i1 = new Integer(1);

        // JDK1.5 or above
        Integer i2 = 10;

        System.out.println(i1);
        System.out.println(i2);
        System.out.println("----------------[Gorgeous split line]----------------");

        // 2. Unpacking
        // Unpacking before JDK1.5: integer - > int
        int a = i2.intValue();

        // Unpacking of JDK1.5 and above: integer - > int
        int b = i2;

        System.out.println(a);
        System.out.println(b);

        // Observe what happens to the following code
        // Packing
        Integer i3 = 10;
        // Equivalent to: i3 = i3 + 20 first unpack i3 into int, then add it to 20, and then box the result int type into Integer
        i3 += 20;
    }
}

5, Date and Calendar

  • Date class
Date explain:java.util Class under package, It represents the date class,It can be accurate to milliseconds,Most of the methods inside are out of date,Has been Calendar Replaced.

   Construction method:
            public Date();    // Get current time           

   Member method:
            public void setTime(long time);      //Set the time in milliseconds
            public long getTime();      				 //Gets the time in milliseconds

   details:
        1. Direct printing Date object, We are not used to the format, Can you change it to the format we are used to.
           sure, SimpleDateFormat Can achieve.
        2. Look through API find Date Most methods are outdated, cover Calendar Replaced.
            Calendar: Calendar Class.
        3. Gets the current time in milliseconds.
            long time = System.currentTimeMillis();

  • code
package demo08_date;
import java.util.Date;

/*
    Case: demonstrate the usage of Date class
 */
public class Demo01 {
    public static void main(String[] args) {
        //Demonstrate the use of Date
      
      	// 1. Get the current time
        Date d = new Date();
        System.out.println(d);      //Thu Sep 09 17:41:30 CST 2021
        System.out.println(d.getTime());  //1631180490798, how many milliseconds are there in total from 1970 to the current time
        System.out.println("--------------------");
				
        // 2. Set time
        Date d2 = new Date(1631180490798L);
        System.out.println(d2); //Thu Sep 09 17:41:30 CST 2021
        System.out.println("--------------------");

        //3. Obtain the current time millisecond value, which is the actual development practice
        long time = System.currentTimeMillis();
        System.out.println(time);
    }
}

2. Usage of simpledateformat time format class

summary:
	It represents a date formatting class, which is mainly used to format or parse dates.

Construction method:
	public SimpleDateFormat();			Default template
	public SimpleDateFormat(String pattern) Specify template

Member method:
	Date -> String: 	format
		format();
	String -> Date:		analysis
		parse();
Case:
	custom DateUtils Tool class.
  • code
package demo08_SimpleDateFormat;

import java.text.SimpleDateFormat;
import java.util.Date;

/*
    Case: demonstrate the usage of SimpleDateFormat
    Case:
        Custom DateUtils tool class
 */
public class Demo01 {
    public static void main(String[] args) throws Exception{
        // 1. Get current journal
        Date d = new Date();
        System.out.println(d);
        System.out.println("===================");

        //2. Demo: Date conversion - String:
        // Format date: yyyy-mm-dd HH mm SS
        // Create a SimpleDateFormat object
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String new_date = sdf.format(d);
        System.out.println(new_date);
        System.out.println("=================");

        //3. Presentation: String - Date:
        String s = "2021 October 10, 2015:50:50";
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
        //There is an exception here. You need to throw an exception. Shortcut: alt + ENTER
        Date d2 = sdf2.parse(s);
        System.out.println(d2);
    }
}

3. Basic use of calendar

case: demonstration Calendar Usage of.

Calendar Introduction:
	summary:
		It represents the calendar class. It is an abstract class in which most methods are replaced Date Class.
	Member constants:
		public static final int YEAR;
		public static final int MONTH;
        public static final int DATE;
        public static final int DAY_OF_MONTH;
        public static final int DAY_OF_YEAR;

	Member method:
		public static Calendar getInstance();	obtain Calendar Class.
		public int get(int field);      According to the specified calendar field, Get value.
		public int set(int year, int month, int day);  Set time.
  • code
package demo08_SimpleDateFormat;

import java.util.Calendar;

/*
    Case: demonstrate the use of Calendar
 */
public class Demo02 {
    public static void main(String[] args) {
        //The abstract class is a subclass object of the polymorphic Calendar class
        Calendar c = Calendar.getInstance();

        //Get time field
        System.out.println(c.get(Calendar.YEAR));   //2021
        System.out.println(c.get(Calendar.MONTH));  //8. Month range in Java: 0 ~ 11
        System.out.println(c.get(Calendar.DATE));   //9
        System.out.println(c.get(Calendar.DAY_OF_MONTH));   //9
        System.out.println(c.get(Calendar.DAY_OF_YEAR));    //252
        System.out.println("-----------------------------");
    }
}

4. Exception handling

Anomaly introduction:
        summary:
            Java in, All abnormal conditions are collectively referred to as exceptions.
        classification:
            Parent class: Throwable
                Exception:  This is what we often call anomaly.
                    Runtime exception: refer to RuntimeException And its subclasses.
                    Compile time exception: Refers to right and wrong RuntimeException And its subclasses.
        What is the difference between compile time exceptions and runtime exceptions?
            Compile time exception: Must handle, To compile.
            Runtime exception: Do not handle, It can also be compiled, But the operation reports an error.

        JVM How are exceptions handled by default?
            1. The type of exception, reason, Print location to console.
            2. And terminate the execution of the program.

        Exception handling:
            Mode 1: Declaration throws an exception, throws
                Vernacular translation: Tell me to call here, I have a problem here, Who calls, Who handles it.
                After processing, Program termination, JVM This is the default.

            Mode 2: Catch exception, After processing, The program continues.
                try {
                    Possible problem codes;
                } catch(Exception e) {
                    e.printStackTrace();  //Print the type, location and reason of the exception
                } finally {
                     It contains code that must be executed.
                }
  • code
package com.itheima.demo09_exception;

import java.text.ParseException;
import java.text.SimpleDateFormat;

/*
    Case: demonstration exception
 */
public class Demo01 {
    public static void main(String[] args) {
        //Runtime exception
        //System.out.println(1 / 0);      // Arithmeticexception (arithmetic exception)
        //System.out.println("see if I did it?");

        //Compile time exception
        //SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
        //Sdf2.parse ("1 January 2020");

        try{
            //Codes that may cause problems;
            show();
        }catch (Exception e){
            e.printStackTrace();  //Print the type, location and reason of the exception
        }finally {
            //To release resources, normally, the code inside will always execute
        }
        System.out.println("Look, did I do it?");
    }
    public static void show() throws ParseException {
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
        sdf2.parse("2020/1/1");
    }

}

Topics: Java Big Data hive JSON