Java exception handling, string handling, formatting, time handling, regular expressions, StringBuilder class (thousand-word long text)

This article has participated in the "Newcomer Creation Ceremony" activity, and started the road of Nuggets creation together

Java exception handling, string handling, formatting, time handling, regular expressions, StringBuilder class (thousand-word long text)

exception handling

In order to solve the errors in Java programs and ensure the readability and maintainability of the program, we need to use exception handling statements: try-catch-finally syntax:

try{
	可能会出错的代码块
}
catch(Exception error){
	异常处理方式
}
finally{
	后续执行代码
}
复制代码

When there is an error in the code in try, the program will go to catch to execute processing, and finally execute finally, the code in finally will be executed regardless of whether the program has an error or not. When the finally statement is not executed:

  1. The code in finally throws an exception
  2. Use System.exit() to exit the Java virtual machine before finally
  3. The thread where the program is located dies
  4. turn off the CPU

Common exception classes in Java

在这里插入图片描述

custom exception

Steps to customize the exception class in the program:

  1. Create custom exception class
  2. The method throws an exception object through the throw keyword
  3. If the exception is handled in the method that currently throws the exception, you can use try-catch to capture and handle it. Otherwise, use the throws keyword at the method declaration to indicate the exception to be thrown to the method caller, and continue to the next step.
  4. Catch and handle the exception in the caller of the method where the exception occurred

Create custom exception syntax:

public class 自定义的错误类名 extends Exception{
    public 自定义的错误类名(String error_code){
        super(error_code);
    }
}
复制代码

Custom exception throwing and catching syntax:

public class 自定义类名 {
     static 数据类型 方法名(形参)throws 自定义错误类名{
        if (条件){
            throw new 自定义错误类名(参数);
        }
        return 返回值;
    }
    public static void main(String[] args) {
		try{
		}
		catch(自定义错误类名 对象名){
		}
    }
复制代码

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克限购了!");
        }
        return n1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请问你要买多少克鸡蛋?");
        try {
            int num = limit(sc.nextInt());
        }catch (My_Exception e){
            System.out.println(e);
        }
    }
}
复制代码

Program display:在这里插入图片描述

throw exception in method

1. Use the throws keyword to throw exceptions When declaring a method, it is used to specify the exceptions that the method may throw

public class 自定义的错误类名 extends Exception{
    public 自定义的错误类名(String error_code){
        super(error_code);
    }
}
复制代码

Multiple exceptions can be separated by commas 2. Use the throw keyword to throw exceptions in the method body, throw an exception object, and terminate immediately when the program executes the throw statement. You can use throws to specify exceptions for processing, and use try- The catch statement catches the exception.

runtime exception

type illustrate
NullPointerException null pointer exception
ArrayIndexOutOfBoundsException Array subscript out of bounds exception
ArithmeticException Arithmetic exception
ArrayStoreException Exception thrown when array contains incompatible values
IllegalArgumentException Illegal parameter exception
SecurityException 安全性异常
NegativeArraySizeException 数组长度为负异常
## 异常的使用原则
  1. 在当前方法声明中使用try-catch进行捕获异常
  2. 一个方法被覆盖时,覆盖它的方法必须抛出相同的异常或异常的子类
  3. 若父类抛出多个异常,覆盖方法就要抛出那些异常的一个子集,不能抛出新的异常

字符串

在这里插入图片描述

String类

单字符使用char型存储 多字符使用String型存储 String最多可以存储2^32-1个字节的文本内容 1.声明字符串 语法:

String str = "你要输入的内容";
复制代码

2.创建字符串 Java中将字符串作为对象来处理,所以可以像创建其他类对象一样来创建字符串对象 语法:

  1. String(char a[])
char a[] = {'g','o','d'};
							<=>	String s = new String("god");
String s = new String(a);
复制代码
  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);
复制代码
  1. 我最推荐
String str;
				<=> String str = "good"; 
str = "good";
复制代码

连接字符串

1.连接多个字符串 使用+运算符即可,可以连接并产生一个新的字符串对象。 例子:

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);
    }
}
复制代码

程序展示: 在这里插入图片描述

2.连接其他数据类型 若字符串和其他数据类型相连接就会把其他类型的数据转化为字符串型 例子:

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);
    }
}
复制代码

程序展示: 在这里插入图片描述

获取字符串信息

1.获取字符串的长度 使用String类中的length()方法可以获取字符串的长度 语法:

String str = "something you enter";
int len = str.length();
复制代码

例子:

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("字符串长度为:"+ size);
    }
}
复制代码

程序展示: 在这里插入图片描述 2.字符串查找 注意: 字符串索引:是从0开始的! String类中的查找字符串方法:

  1. indexOf()

indexOf方法返回的是搜索的字符或字符串首次出现的位置 语法(例子):

String str = "something you enter";
str.indexOf('y');
复制代码
public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        int pos = str.indexOf('y');
        System.out.println("y出现的位置是:"+ pos);
    }
}

复制代码

程序展示: 在这里插入图片描述 2. lastIndexOf() lastIndexOf()方法返回的是搜索的字符或字符串最后一次出现的位置 语法(例子):

String str = "something you enter";
str.lastIndexOf('e');
复制代码
public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        int pos = str.lastIndexOf('e');
        System.out.println("y出现的位置是:"+ pos);
    }
}
复制代码

程序展示: 在这里插入图片描述 3.获取指定索引位置的字符 使用charAt()方法可以将指定索引处的字符返回 语法(例子):

 String str = "something you enter";
        char s = str.charAt(5);
复制代码
public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        char s = str.charAt(5);
        System.out.println("y出现的位置是:"+ s);
    }
}

复制代码

程序展示: 在这里插入图片描述

字符串操作

1.获取字符串 String类中的substring()方法可以对字符串进行截取(下标)

  1. substring(int beginIndex)

返回指定索引开始到结尾的字符串

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);
    }
}
复制代码

程序展示: 在这里插入图片描述

  1. substring(int beginIndex,int endIndex)

返回开始到结束的范围内的字符串(包括开始不包括结尾)

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);
    }
}
复制代码

程序展示: 在这里插入图片描述 2.去除空格 使用trim()方法返回字符串副本忽略前面和后面的空格 语法(例子):

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());
    }
}

复制代码

程序展示: 在这里插入图片描述 3.字符串替换 使用replace()方法可以将指定字符串进行替换 语法(例子):

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);
    }
}
复制代码

程序展示: 在这里插入图片描述 4.判断字符串的开始与结尾

  1. startsWith()方法

用于判断当前字符串的前缀是否为参数指定字符串,返回Boolean型

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        System.out.println(str.startsWith("somet"));
    }
}
复制代码

程序展示: 在这里插入图片描述

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        System.out.println(str.startsWith("sometoooo"));
    }
}
复制代码

程序展示: 在这里插入图片描述

  1. endsWith()方法

用于判断当前字符串的后缀是否为参数指定字符串,返回Boolean型

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        System.out.println(str.endsWith("sometoooo"));
    }
}
复制代码

程序展示: 在这里插入图片描述

public class work_2 {
    public static void main(String[] args) {
        String str = "something you enter";
        System.out.println(str.endsWith("er"));
    }
}
复制代码

程序展示: 在这里插入图片描述 5.判断字符串是否相等 判断字符串是否相等不能单纯使用 == 运算符 原因: == 运算符是用于判断内存地址的! 方法:

  1. equals()方法

判断: 若两个字符串具有相同的字符和长度则返回true否则是false(区分大小写) 语法(例子):

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));
    }
}
复制代码

程序展示: 在这里插入图片描述 2. equalsIngnoreCase()方法 若两个字符串具有相同的字符和长度则返回true否则是false(不区分大小写)

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));
    }
}
复制代码

程序展示: 在这里插入图片描述 6.按字典顺序比较两个字符串 使用compareTo()方法可以按照字典顺序对两个字符串进行比较(基于字符 的Unicode值)简而言之:compareTo()方法就是对两个字符串的位置进行比较,比如: a与b相比返回值为-1因为a在b前一位 返回值为负数说明在前,为正说明在后,相同则返回0! 注意: 只比较首字母,若首字母相同则比较后续不同的字母顺序! 语法(例子):

public class work_2 {
    public static void main(String[] args) {
        String str1 = "a";
        String str2 = "b";
        String str3 = "e";
        System.out.println("a与b相比,a在b的:"+str1.compareTo(str2));
        System.out.println("e与a相比,e在a的:"+str3.compareTo(str1));
    }
}
复制代码

程序展示: 在这里插入图片描述 例子:

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("answer与boy相比,answer在boy的:"+str1.compareTo(str2));
        System.out.println("eye与answer相比,eye在answer的:"+str3.compareTo(str1));
        System.out.println("eye与ear相比,eye在ear的:"+str3.compareTo(str4));
    }
}
复制代码

程序展示: 在这里插入图片描述

7.字母的大小写转换

  1. toLowerCase()方法全部转化为小写字母
  2. toUpperCase()方法全部转化为大写字母

语法(例子):

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());
    }
}
复制代码

程序展示: 在这里插入图片描述 8.字符串分割 使用split()方法按照指定字符或字符串进行分割 语法(例子):

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+"|");
        }
    }
}

复制代码

程序展示: 在这里插入图片描述

格式化字符串

使用String类中的format()方法用于创建格式化字符串

  1. format(String format,Object...args)

args:格式字符串中由格式说明符引用的参数,若有格式说明符以外的参数,则忽略,此参数的数目是不定的! 2. format(Local 1,String format,Object...args) l:这不是数字1是字母l,表示格式化过程中要用的语言环境,若l为null则不进行本地化

1.日期格式化 注意: 需要导入库——import java.util.Date; 目的: 为了输出满意的日期(年月日) 常用日期格式化转换符:

转换符 说明
%te 一个月中的某一天(1~31)
%tb 指定语言环境的月份简称
%tB 指定语言环境的月份全称
%ta 指定语言环境的星期几简称
%tA 指定语言环境的星期几全称
%tc 包括全部日期和时间信息
%tj 一年中的第几天
%tY 4位年份
%ty 2位年份
%td 一个月中的第几天
%tm 月份
语法(例子):
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("今天的日期是:" + year + month + day);
    }
}

复制代码

程序展示: 在这里插入图片描述 2.时间格式化 注意: 需要导入库——import java.util.Date; 目的: 为了输出满意的时间(时分秒毫秒) 常用日期格式化转换符:

转换符 说明
%tH 2位数字的24时制的小时 (00~23)
%tI(大写i) 2位数字的12时制的小时 (01~12)
%tk 2位数字的24时制的小时 (0~23)
%tl(小写L) 2位数字的12时制的小时 (1~12)
%tL 3位数字的毫秒数(000~999)
%tM 2位数字的分钟数(00~59)
%tS 2位数字的秒数(00~60)
%tN 9位数字的微秒数(000000000~999999999)
%tp 指定语言环境的上下午
%tZ 时区缩写形式的字符串(CST)
%tz 相对于GMT RFC 82格式的数字时区偏移量
%ts 1970-01-01 00:00:00到现在经过的秒数
%tQ 1970-01-01 00:00:00到现在经过的毫秒数
语法(例子):
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("今天的日期是:" + year + month + day);
        System.out.println("现在是:"+hour+minute+second);
    }
}
复制代码

程序展示: 在这里插入图片描述 记忆使用方法(常用): 日期(除了年t后全小写): year——%tY month——%tm day——%td 时间(t后全大写): hour——%tH minute——%tM second——%tS 常用日期时间组合格式:

转换符 说明
%tF 年-月-日格式年份是四位
%tD 月/日/年格式年份是二位
%tc 全部日期和时间信息
%tr 时:分:秒AM(PM)格式12小时制
%tT 时:分:秒格式24小时制
%tR 时:分格式24小时制
常用:
form——%tF
CST(全部日期时间)——%tc
3.常规类型格式化
转换符 说明
-- --
%b,%B 结果格式化为布尔型
%h,%H 结果格式化为散列码
%s,%S 结果格式化为字符串型
%c,%C 结果格式化为字符型
%d 结果格式化为十进制整数
%o 结果格式化为八进制整数
%x,%X 结果格式化为十六进制整数
%e 结果格式化为计算机科学记数法表示的十进制数
%a 结果格式化为带有效位数和指数的十六进制浮点数
%n 结果为特定平台的行分隔符
%% 结果为%
## 使用正则表达式
正则表达式通常用于判断语句中,用于检查某一字符串是否满足某一格式,正则表达式是含有一些具有特殊意义字符的字符串,这些特殊字符称为正则表达式的元字符。
正则表达式的元字符:
元字符 正则表达式中的写法
-- --
. .
\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}
正则表达式中,可以使用方括号[],括起多个字符来表示一个元字符,该元字符可以代表方括号中任何一个字符
例子:
[^357]:表示除了3,5,7以外任何数字
[a-i]:表示a~i中任何一个字母
[a-o&&[def]]:表示字母d,e,f(交运算)
[a-e&&[^c]]表示a,b,d,e(差运算)
限定修饰符(加在后eg.A?):
限定修饰符 意义
-- --
? 0次或1次
* 0次或1次
+ 一次或多次
{n} 正好出现n次
{n,} 至少出现n次
{n,m} 出现n~m次
示例使用P171判断Email地址合法的例子:
在这里插入图片描述
## 字符串生成器
创建成功的字符串对象其长度是固定的,不能被随意改变和编译,使用+运算符可以附加新字符串但会生成一个新的String实例,若重复地对字符串进行修改会极大增大系统的开销,以此增加了StringBuilder类。
StringBuilder类可以频繁地对字符串进行修改
1 .append()方法
用于在字符串中追加内容
语法(例子):
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);
    }
}
复制代码

程序展示: 在这里插入图片描述 2.insert(int beginIndex,args)方法 该方法用于向字符串相应位置添加字符串 beginIndex:开始位置,比如5,那么索引位置就是在第5位开始 在这里插入图片描述 args:要插入的内容

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());
    }
}
复制代码

程序展示: 在这里插入图片描述 3.delete(int beginIndex,int endIndex) 用于固定位置删除中间的字符

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());
    }
}
复制代码

程序展示: 在这里插入图片描述 在这里插入图片描述

Guess you like

Origin juejin.im/post/7084038947029909534