Java Novice Learning Guide [day14]---Commonly Used Classes-Exceptions-Regular Expressions

1. Get random numbers

Four ways to get random numbers:

1. Use the random method in Math

static double random() 
          //返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。 

2. Use nextInt in the Random class

 int nextInt(int n) 
  //返回一个伪随机数,它是取自此随机数生成器序列的、在 0(包括)和指定值(不包括)之间均匀分布的 int 值。 

3. Use nextInt in the ThreadLocalRandom class (find in api 1.8)

int nextInt() 
//返回一个随机 int价值。  

4. RandomUUID in the UUID class

static UUID randomUUID() 
//获取类型 4(伪随机生成的)UUID 的静态工厂。 

2. Date class

This class provides two construction methods, you can create objects to call methods

Date()  //分配 Date 对象并初始化此对象,以表示分配它的时间(精确到毫秒)。
Date(long date)  //分配 Date 对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以来的指定毫秒数。

Date formatting: SimpleDateFormat (for formatting (date -> text), parsing (text -> date) and normalization)

(Date-----> text): use the format in the parent class DateFormat

(Text-----> Date): Use parse directly, but pay attention to the format

3. Abnormal

Exception: Exception is abnormal

Error: error at the jvm level, which is more serious

Classification of exceptions:

1. Runtime exception: No error will be reported during compilation, but error will be reported during runtime. eg. Array out-of-bounds exception, null pointer exception (because the null object calls method), arithmetic exception, type conversion exception

2. Non-runtime exception: An error will be reported during compilation. eg. At present, only SimpleDateFormat calls parse when parsing exceptions

Exception handling method:

1. Throw an exception: If an exception occurs in the method, throw it to the method, if the method is called, throw it to the caller, and finally throw it to the jvm that has not been processed (throws after the method)

2. Catch exceptions: Runtime exceptions are generally captured by grabbing exceptions and by try...catch. If the code that may be wrong is really wrong, the statement after the catch is executed, which can be nested. If there is still some code that needs to be executed, finally can be added.

try{
    
    
    //可能出错的代码
}catch(异常对象){
    
    
    //处理办法
    //1、通过对象直接打印错误信息
    //2、将异常信息记录到文件
    //3、抛出异常到jvm
}finally{
    
    
    //不论代码是否出错都会被执行,除非在finally之前jvm虚拟机先停止
}
//注意如果上述结构作为方法有返回值,一定要注意编译只看类型

Custom exceptions: In order to meet certain business needs, custom exceptions can be constructed and implemented through inheritance

4. Regular expressions

Pattern matches in the string class currently in contact

Guess you like

Origin blog.csdn.net/WLK0423/article/details/109565367