This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together

Java Exception Handling, String Handling, Formatting, Time Handling, Regular Expressions, StringBuilder Classes (Swastika)

Exception handling

To resolve errors in Java programs and make them readable and maintainable, we need to use exception handling statements: try-catch-finally syntax:

try{block of code that could go wrong}catch(Exception error){Exception handlingfinally{subsequent execution code}Copy the code

When something goes wrong ina try, the program goes to a catch and finally, and the code in finally executes whether or not the program fails. Finally statement not executed:

  1. The code in finally has an exception
  2. Exit the Java virtual machine using system.exit () before finally
  3. The thread on which the program resides dies
  4. Shut down the CPU

Common exception classes in Java

Custom exception

Steps for customizing an exception class in your program:

  1. Create a custom exception class
  2. Method throws an exception object through the throw keyword
  3. If an exception is handled in a method that throws an exception, you can use try-catch to catch and process the exception. Otherwise, specify the exception to be thrown to the method caller through the throws keyword on the method declaration, and proceed to the next step
  4. Catch and handle the exception in the caller of the method in which it occurs

Create custom exception syntax:

public classCustom error class nameextends Exception{
    publicCustom error class name (String error_code){super(error_code); }}Copy the code

Custom exception throw and catch syntax:

public classCustom class name{
     staticData type method name (parameter)throwsCustom error class name {if(conditions) {throw newCustom error class names (parameters); }returnThe return value. }public static void main(String[] args) {
		try{}catch(Custom error class name object name){}}Copy the code

Example:

import java.util.Scanner;

public class error_deal {
    static int limit(int n1) throws My_Exception {
        if (n1 > 1500) {
            throw new My_Exception("1500 grams over the limit!");
        }
        return n1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("How many grams of eggs do you want, please?");
        try {
            int num = limit(sc.nextInt());
        }catch(My_Exception e){ System.out.println(e); }}}Copy the code

Program display:

Throw an exception in a method

1. Throws exceptions Using the keyword when declaring a method, it specifies the exceptions that the method may throw

public classCustom error class nameextends Exception{
    publicCustom error class name (String error_code){super(error_code); }}Copy the code

Use the throw keyword to throw an exception object in the method body. When the program executes to the throw statement, it terminates immediately. You can use the throw statement to specify exceptions for processing, and use the try-catch statement to catch exceptions.

Runtime exception

species instructions
NullPointerException Null pointer exception
ArrayIndexOutOfBoundsException Array index out of bounds exception
ArithmeticException Arithmetic exception
ArrayStoreException An exception thrown by an array containing incompatible values
IllegalArgumentException Invalid parameter abnormal
SecurityException Security anomaly
NegativeArraySizeException Array length is negative exception
## The rules for using exceptions
  1. Use try-catch to catch exceptions in the current method declaration
  2. When a method is overridden, the overriding method must throw the same exception or a subclass of the exception
  3. If the parent class throws more than one exception, the override method throws a subset of those exceptions and cannot throw new ones

string

The String class

Single-character char storage Multi-character String storage String can store up to 2^32-1 bytes of text 1. Declare string syntax:

String str = "What are you going to type in?";
Copy the code

Java treats strings as objects, so you can create string objects just like any other class of objects:

  1. String(char a[])
char a[] = {'g'.'o'.'d'};
							<=>	String s = new String("god");
String s = new String(a);
Copy the code
  1. String(char a[] , int start , int length)
char a[] = {'g'.'o'.'o'.'d'};
							<=>	String s = new String("oo");
String s = new String(a,1.2);
Copy the code
  1. I recommend most
String str;
				<=> String str = "good"; 
str = "good";
Copy the code

Connection string

1. Concatenate multiple strings using the + operator to concatenate and produce a new string object. Example:

public class work_2 {
    public static void main(String[] args) {
        String s1 = "I LOVE ";
        String s2 = "JAVA";
        String s3 = "\t hello world"; String s = s1 + s2 + s3; System.out.println(s); }}Copy the code

Program display:

2. Concatenate other data types. Concatenate other data types to convert other data types to strings.

public class work_2 {
    public static void main(String[] args) {
        String s1 = "I LOVE ";
        String s2 = "JAVA";
        String s3 = "\n hello world";
        int s4 = 20210728;
        double s5 = 20.000023; String s = s1 + s2 + s4 + s3 + s5; System.out.println(s); }}Copy the code

Program display:

Get string information

We can use the length() method of the String class to get the String length syntax:

String str = "something you enter";
int len = str.length();
Copy the code

Example:

public class work_2 {
    public static void main(String[] args) {
        String s1 = "I LOVE ";
        String s2 = "JAVA";
        String s3 = "\n hello world";
        int s4 = 20210728;
        double s5 = 20.000023;
        String s = s1 + s2 + s4 + s3 + s5;
        int size = s.length();
        //System.out.println(s);
        System.out.println("The string length is:"+ size); }}Copy the code

Program display: 2. String searchNote: string index:It starts at zero!Finding a String method in the String class:

  1. indexOf()

The indexOf method returns the syntax for the first occurrence of the searched character or string (example) :

String str = "something you enter";
str.indexOf('y');
Copy the code
public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        int pos = str.indexOf('y');
        System.out.println("Where y appears is:"+ pos); }}Copy the code

Program display: 2. lastIndexOf() The lastIndexOf() method returns the position of the last occurrence of the searched character or stringSyntax (example) :

String str = "something you enter";
str.lastIndexOf('e');
Copy the code
public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        int pos = str.lastIndexOf('e');
        System.out.println("Where y appears is:"+ pos); }}Copy the code

Program display: 3. Obtain the character of the specified index positionUse the charAt() method to return the character at the specified index (example) :

 String str = "something you enter";
        char s = str.charAt(5);
Copy the code
public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        char s = str.charAt(5);
        System.out.println("Where y appears is:"+ s); }}Copy the code

Program display:

String manipulation

The substring() method of the String class intercepts strings (subscripts).

  1. substring(int beginIndex)

Returns a string from the beginning to the end of the specified index

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        String str_cut = str.substring(4); System.out.println( str_cut); }}Copy the code

Program display:

  1. substring(int beginIndex,int endIndex)

Returns a string in the range from beginning to end (including beginning but not ending)

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        String str_cut = str.substring(4.12); System.out.println(str_cut); }}Copy the code

Program display: 2. Remove whitespaceUse the trim() method to return a copy of the string ignoring the preceding and following whitespace syntax (example) :

public class work_2 {
    public static void main(String[] args) {
        String str = " something you enter "; System.out.println(str.length()); System.out.println(str.trim()); System.out.println(str.trim().length()); }}Copy the code

Program display: 3. String replacementUse the replace() method to replace the specified string syntax (example) :

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        String new_str = str.replace("someth"."new"); System.out.println(new_str); }}Copy the code

Program display: 4. Determine the beginning and end of the string

  1. StartsWith () method

Returns Boolean to determine whether the current string prefix is the specified string

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        System.out.println(str.startsWith("somet")); }}Copy the code

Program display:

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        System.out.println(str.startsWith("sometoooo")); }}Copy the code

Program display:

  1. EndsWith () method

Returns Boolean to determine whether the suffix of the current string is the string specified for the argument

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        System.out.println(str.endsWith("sometoooo")); }}Copy the code

Program display:

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        System.out.println(str.endsWith("er")); }}Copy the code

Program display: 5. Check whether the strings are equalThe == operator cannot be used to determine whether strings are equal.The == operator is used to determine memory locations!Methods:

  1. The equals () method

Judgment: Return true if two strings have the same character and length otherwise false (case sensitive) syntax (example) :

public class work_2 {
    public static void main(String[] args) {
        String str1 = "good";
        String str2 = "mod";
        String str3 = "good"; System.out.println(str1.equals(str2)); System.out.println(str1.equals(str3)); }}Copy the code

Program display:2. EqualsIngnoreCase () returns true if two strings have the same character and length otherwise false (case insensitive)

public class work_2 {
    public static void main(String[] args) {
        String str1 = "good";
        String str2 = "good";
        String str3 = "GooD"; System.out.println(str1.equalsIgnoreCase(str2)); System.out.println(str1.equalsIgnoreCase(str3)); }}Copy the code

Program display: 6. Compare two strings in dictionary orderThe compareTo() method compares two strings in lexicographical order (based on the Unicode value of the character). In short: The compareTo() method compares the positions of two strings, such as: A returns -1 compared to b because a is one bit before B and it returns negative meaning before b, positive meaning after,If so, return 0!Note:Only compare the first letter, if the first letter is the same, compare the subsequent different alphabetic order!Syntax (example) :

public class work_2 {
    public static void main(String[] args) {
        String str1 = "a";
        String str2 = "b";
        String str3 = "e";
        System.out.println("As compared with B, A is inferior to B:"+str1.compareTo(str2));
        System.out.println("E compared with A, e is in a:"+str3.compareTo(str1)); }}Copy the code

Program display:Example:

public class work_2 {
    public static void main(String[] args) {
        String str1 = "answer";
        String str2 = "boy";
        String str3 = "eye";
        String str4 = "ear";
        System.out.println(Can you answer this question? Can you answer this question?+str1.compareTo(str2));
        System.out.println("Eye vs. answer, eye is in answer:"+str3.compareTo(str1));
        System.out.println("Eye as opposed to ear, eye in ear:"+str3.compareTo(str4)); }}Copy the code

Program display:

7. Case conversion of letters

  1. The toLowerCase() method is converted to all lowercase letters
  2. The toUpperCase() method is converted to all uppercase letters

Syntax (example) :

public class work_2 {
    public static void main(String[] args) {
        String str1 = "answer";
        String str2 = "BOY"; System.out.println(str1.toUpperCase()); System.out.println(str2.toLowerCase()); }}Copy the code

Program display: 8. String splittingUse the split() method to split the syntax by the specified character or string (example) :

public class work_2 {
    public static void main(String[] args) {
        String str1 = "something , you , enter : I LOVE JAVA";
        String[] first = str1.split(":");
        String[] second = str1.split(",".3);
        for (int i = 0; i< first.length; i++){ System.out.print("|"+first[i]+"|");
        }
        System.out.println();
        for (String a:second){
            System.out.print("|"+a+"|"); }}}Copy the code

Program display:

Formatted string

Use the format() method in the String class to create a formatted String

  1. format(String format,Object… args)

Args: parameters in a format string referenced by a format specifier. If there are any parameters other than the format specifier, ignore them. The number of these parameters is variable! 2. format(Local 1,String format,Object… Args) l: this is not the number 1 but the letter L, indicating the locale to be used in the formatting process. If L is null, no localization will be performed

Import java.util.Date; import java.util.Date; Purpose: To output a satisfactory date (year, month, day)

Conversion operators instructions
%te Day of the month (1-31)
%tb Specifies the abbreviation of the month for the locale
%tB Specifies the full name of the month for the locale
%ta Specifies the day of the week abbreviation for the locale
%tA Specifies the full name of the day of the week for the locale
%tc Includes full date and time information
%tj The day of the year
%tY The four year
%ty Two years
%td The day of the month
%tm in
Syntax (example) :
import java.util.Date;

public class work3 {
    public static void main(String[] args) {
        Date data = new Date();
        String year = String.format("%tY", data);
        String month = String.format("%tm", data);
        String day = String.format("%td", data);
        System.out.println("Today's date is:"+ year + month + day); }}Copy the code

Program display: 2. Time formattingNote: You need to import the library —import java.util.Date;Purpose: To output a satisfactory time (hour, minute, second, millisecond)

Conversion operators instructions
%tH 2-digit 24-hour hours (00 to 23)
%tI (capital I) 2-digit 12-hour hours (01 to 12)
%tk 2-digit 24-hour hours (0 to 23)
%tl (lowercase L) 2-digit 12-hour hours (1 to 12)
%tL 3-digit number of milliseconds (000 to 999)
%tM 2-digit minutes (00 to 59)
%tS 2-digit number of seconds (00 to 60)
%tN 9-digit microseconds (000000000 to 999999999)
%tp Specify the morning and afternoon of the locale
%tZ Time zone abbreviated string (CST)
%tz Indicates the offset from the digital time zone in GMT RFC 82 format
%ts 1970-01-01 00:00:00 Number of seconds elapsed since the present
%tQ 1970-01-01 00:00:00 Number of milliseconds since the present
Syntax (example) :
public class work3 {
    public static void main(String[] args) {
        Date data = new Date();
        String year = String.format("%tY", data);
        String month = String.format("%tm", data);
        String day = String.format("%td", data);
        String hour = String.format("%tH",data);
        String minute = String.format("%tM",data);
        String second = String.format("%tS",data);
        System.out.println("Today's date is:" + year + month + day);
        System.out.println("现在是:"+hour+minute+second); }}Copy the code

Program display:Memory Usage (common) : Date (except all lowercase after t) : Year — %tY month — %tm day — % TD time (all uppercase after T) : hour — %tH minute — %tm second — %tS

Conversion operators instructions
%tF Year – month – day format Year is four digits
%tD Month/day/year format Year is two digits
%tc Full date and time information
%tr Hour: Minute: second AM (PM) format In the 12-hour format
%tT Hour: minute: second format In the 24-hour system
%tR Hour: in 24-hour format
Commonly used:
The form – % tF
CST (all date and time) — % TC
3. General type formatting
Conversion operators instructions
% % b, b The result is formatted as a Boolean
% % h, h The result is formatted as a hash code
% s, % s The result is formatted as a string
% % c, c The result is formatted as a character
%d The result is formatted as a decimal integer
%o The result is formatted as an octal integer
% % x, x The result is formatted as a hexadecimal integer
%e The result is formatted as a decimal number in computer science notation
%a The result is formatted as a hexadecimal floating-point number with significant digits and exponents
%n The result is a platform-specific line separator
% % The results for the %
## Use regular expressions
A regular expression is usually used in a statement to check whether a string meets a certain format. A regular expression is a string containing special characters, which are called metacharacters of a regular expression.
Metacharacters for regular expressions:
metacharacters Notation in a regular expression
. .
\d \\d
\D \\D
\s \\s
\S \\S
\w \\w
\W \\W
\p{Lower} \\p{Lower}
\p{Upper} \\p{Upper}
\p{ASCII} \\p{ASCII}
\p{Alpha} \\p{Alpha}
\p{Digit} \\p{Digit}
\p{Alnum} \\p{Alnum}
\p{Punct} \\p{Punct}
\p{Graph} \\p{Graph}
\p{Print} \\p{Print}
\p{Blank} \\p{Blank}
\p{Cntrl} \\p{Cntrl}
In a regular expression, square brackets [] can be used to enclose multiple characters to represent a metacharacter. The metacharacter can represent any character in the square brackets
Example:
[^357] : indicates any number except 3, 5, and 7
[a-i]: indicates any letter from a to I
[a-o&&[def]]: represents the letters D, e, f (intersection operation)
[^c]] a, b, d, e
Qualifier (appended to eg.A?) :
Qualified modifier meaning
? Zero or one
* Zero or one
+ One or more times
{n} It happens exactly n times
{n,} At least n times
{n,m} N ~ m times
Example Using P171 to check the Email address is valid:
## String generator
The String object created successfully has a fixed length and cannot be changed or compiled at will. Using the + operator to append new strings but generate a new String instance, the StringBuilder class is added because repeated String modifications can greatly increase the system overhead.
The StringBuilder class can modify strings frequently
1. The append () method
Used to append content to a string
Syntax (example) :
public class work4 {
    public static void main(String[] args) {
        StringBuilder str = new StringBuilder("I LOVE JAVA");
        str.append("this is stringbuilder"); System.out.println(str); }}Copy the code

Program display: 2. Insert (int beginIndex, args) methodThis method is used to add the string beginIndex to the corresponding position in the string, such as 5, so that the index position starts at the fifth digitArgs: What to insert

public class work4 {
    public static void main(String[] args) {
        StringBuilder str = new StringBuilder("I LOVE JAVA");
        str.append("this is stringbuilder");
        str.insert(4."|\tinsert\t|"); System.out.println(str.toString()); }}Copy the code

Program display: 3.delete(int beginIndex,int endIndex)Used to remove intermediate characters in a fixed position

public class work4 {
    public static void main(String[] args) {
        StringBuilder str = new StringBuilder("I LOVE JAVA");
        str.append("this is stringbuilder");
        str.delete(4.10); System.out.println(str.toString()); }}Copy the code

Program display: