16、Java常用类(Pattern、Matcher)、Math类、Random类、System类、BigDecimal类、时间日期类(Date、SimpleDateFormat、LocalDateT

Character包装类

package org.westos.demo;

/**
 * @author lwj
 * @date 2020/5/2 20:05
 */
public class MyTest {
    public static void main(String[] args) {
        Character character = 'c';
        char ch = '0';
        boolean digit = Character.isDigit(ch);
        //判断字符是否为数字字符
        System.out.println(digit);
        //true

        char ch2 = 'A';
        boolean letter = Character.isLetter(ch2);
        //判断字符是否为字母
        System.out.println(letter);
        //true


        boolean upperCase = Character.isUpperCase(ch2);
        //判断字符是否为大写字母,ch2 >= 'A' && ch2 <= 'Z'
        System.out.println(upperCase);
        //true

        char ch3 = 'a';
        boolean lowerCase = Character.isLowerCase(ch3);
        //判断字符是否为小写字母
        System.out.println(lowerCase);
        //true

        char ch4 = ' ';
        boolean spaceChar = Character.isSpaceChar(ch4);
        //判断字符是否是空格
        System.out.println(spaceChar);
        //true
    }
}
'a' = 97
'z' = 122
'A' = 65
'Z' = 90
'0' = 48
'9' = 57
' ' = 32
package org.westos.demo;

/**
 * @author lwj
 * @date 2020/5/2 20:23
 */
public class MyDemo {
    public static void main(String[] args) {
        int a = '0';
        System.out.println(a);
        //48

        int b = 'Z';
        System.out.println(b);
        //90

        int c = 'z';
        System.out.println(c);
        //122

        int d = ' ';
        System.out.println(d);
        //32

        System.out.println((int)'9');
        //57
    }
}

Pattern和Matcher

边界匹配器
^	行的开头
$	行的结尾
\\b	单词边界(就是不是单词字符的地方)
package org.westos.demo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lwj
 * @date 2020/5/3 9:14
 */
public class MyDemo {


    public static void main(String[] args) {
        //Pattern 模式器:封装一个正则表达式
        //Matcher 匹配器

        Pattern compile = Pattern.compile("a*b");
        Matcher matcher = compile.matcher("aaab");
        boolean matches = matcher.matches();
        System.out.println(matches);
        //true


        //如果仅仅是为了看一个字符串符不符合一个正则,调用String类的matches方法
        System.out.println("aaab".matches("a*b"));
        //true


        //但是有时我们还有其他的需求,String类中的方法不足以完成我们的需求,而Pattern和Matcher类可以提供更丰富的针对正则的功能
    }
}
package org.westos.demo;


import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lwj
 * @date 2020/5/2 20:29
 */
public class MyTest {
    public static void main(String[] args) {
        /*
        需求:获取下面这个字符串中由三个字符组成的单词 正则表达式 \\b[a-z]{3}\\b
	    da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?
         */
        String s = "da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?";
        Pattern compile = Pattern.compile("\\b[a-z]{3}\\b");
        //\\b代表单词边界
        Matcher matcher = compile.matcher(s);
        while (matcher.find()) {
            String group = matcher.group();
            System.out.print(group + "---");
            //jia---jin---yao---xia---wan---gao---
        }



        //传统方法,?是关键字符
        String s1 = s.replaceAll("[,\\?]+", " ");
        String[] split = s1.split("[\\s]+");
        //匹配一个或多个空格
        System.out.println(Arrays.toString(split));
        //[da, jia, ting, wo, shuo, jin, tian, yao, xia, yu, bu, shang, wan, zi, xi, gao, xing, bu]
        for (String value : split) {
            if (value.length() == 3) {
                System.out.print(value + "---");
                //jia---jin---yao---xia---wan---gao---
            }
        }
    }
}

匹配网址

package org.westos.demo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lwj
 * @date 2020/5/3 9:52
 */
public class Test {
    public static void main(String[] args) {
        String s = "<a href=\"https://www.cnblogs.com/techflow/\" class=\"lightblue\">TechFlow2019</a> \n" +
                "    发布于 2020-05-03 09:46 \n" +
                "    <span class=\"article_comment\"><a href=\"https://www.cnblogs.com/techflow/p/12820881.html#commentform\" title=\"\" class=\"gray\">\n" +
                "        评论(0)</a></span><span class=\"article_view\"><a href=\"https://www.cnblogs.com/techflow/p/12820881.html\" class=\"gray\">阅读(0)</a></span></div>";
        String regex = "https://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(s);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
        //https://www.cnblogs.com/techflow/
        //https://www.cnblogs.com/techflow/p/12820881.html
        //https://www.cnblogs.com/techflow/p/12820881.html
    }
}

Math类

package org.westos.demo;

/**
 * @author lwj
 * @date 2020/5/3 10:18
 */
public class MyTest {
    public static void main(String[] args) {
        //静态变量
        System.out.println(Math.PI);
        //3.141592653589793
        System.out.println(Math.E);
        //2.718281828459045
        //自然底数


        //静态方法
        System.out.println(Math.abs(-2));
        //2
        System.out.println(Math.max(12, 13));
        //13
        System.out.println(Math.min(12, 13));
        //12
        System.out.println(Math.ceil(3.1));
        //4.0
        //向上取整
        System.out.println(Math.floor(3.1));
        //3.0
        //向下取整
        System.out.println(Math.round(3.666));
        //4
        //四舍五入
        System.out.println(Math.pow(2, 3));
        //8.0
        //获取a的b次幂
        System.out.println(Math.sqrt(4));
        //2.0
        //获取正的平方根
        System.out.println(Math.random());
        //0.607633658548069
        //[0,1)
    }
}

Random类

package org.westos.demo;

import java.util.Arrays;
import java.util.Random;

/**
 * @author lwj
 * @date 2020/5/3 10:29
 */
public class MyDemo {
    public static void main(String[] args) {
        Random random = new Random();

        int num = random.nextInt();
        //生成一个随机的int整数
        System.out.println(num);
        //-88462241


        int i = random.nextInt(10);
        //[0,10)
        System.out.println(i);

        //生成[1,100]的随机整数
        int j = random.nextInt(100) + 1;
        //[0,100) -> [1,101)


        double v = random.nextDouble();
        //生成随机小数,[0,1),作用和Math.random()一样
        System.out.println(v);
        //0.44609725546363777

        byte[] bytes = new byte[10];
        random.nextBytes(bytes);
        //给一个字节数组随机的填充
        System.out.println(Arrays.toString(bytes));
        //[-12, 7, 37, -103, -124, 16, 93, 69, 4, 99]


        Random random1 = new Random(12);
        //带参的构造器,种子生成的随机数每次执行的结果都是一样的,如果是无参的构造器,每次执行的结果是不一样的
        int i1 = random1.nextInt(10);
        System.out.println(i1);
    }
}

此类用于产生随机数,如果用相同的种子创建两个 Random 实例,则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列。

构造方法

public Random()			 没有给定种子,使用的是默认的(当前系统的毫秒值)
public Random(long seed)		 给定一个long类型的种子,给定以后每一次生成的随机数是相同的

System类

System 类包含一些有用的类字段和方法。它不能被实例化。 (构造方法私有化)

public final static InputStream in = null;
public final static PrintStream out = null;
new Scanner(System.in);
System.out.println()
public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);
package org.westos.demo;

import java.util.Arrays;
import java.util.Properties;

/**
 * @author lwj
 * @date 2020/5/3 10:50
 */
public class Test {
    public static void main(String[] args) {
        System.gc();
        //JVM的垃圾回收不需要人为干预,它有自己的垃圾回收算法
        //这个方法只能是加速垃圾回收器回收
        byte[] bytes = {1, 2, 3};
        bytes = null;
        //人为置为null也是为了让垃圾回收器及早回收

        /*System.exit(0);*/
        //退出虚拟机(主线程执行完毕,自动退出虚拟机)
        //Process finished with exit code 0
        //正常退出

        //System.exit(-1);
        //Process finished with exit code -1

        long l = System.currentTimeMillis();
        //获取当前时间的毫秒值,从1970.1.1 00:00:00到此时的毫秒值
        System.out.println(l);
        //1588475601042

        //可以计算某个程序的耗时时间

        int[] arr = {1, 2, 3, 4, 5};
        int[] tar = new int[arr.length];
        System.arraycopy(arr, 0, tar, 0, arr.length);
        //复制数组
        System.out.println(Arrays.toString(tar));
        //[1, 2, 3, 4, 5]


        //获取环境
        String java_home = System.getenv("JAVA_HOME");
        System.out.println(java_home);
        //D:\Java\jdk1.8.0_221

        Properties properties = System.getProperties();
        System.out.println(properties);
        //可以获得的所有property,key:value
        //os.name、user.name等
        System.out.println(properties.getProperty("os.name"));
        //Windows 10
        System.out.println(properties.getProperty("user.name"));
        //shawn

        String user_dir = System.getProperty("user.dir");
        System.out.println(user_dir);
        //获取项目路径
        //E:\XiBuKaiYuan\JavaSEDirectory\0503\常用类
    }
}

BigDecimal类

金融类数字对浮点数的精度要求比较高就不能使用float、double。

package org.westos.demo1;

import java.math.BigDecimal;

/**
 * @author lwj
 * @date 2020/5/3 13:33
 */
public class MyTest {
    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal("1.254888");
        BigDecimal bigDecimal1 = new BigDecimal("3.213123124123232415534");
        BigDecimal multiply = bigDecimal.multiply(bigDecimal1);
        System.out.println(multiply);
        //4.032109650984754879464630192

        BigDecimal add = bigDecimal.add(bigDecimal1);
        System.out.println(add);
        //4.468011124123232415534

        BigDecimal subtract = bigDecimal.subtract(bigDecimal1);
        System.out.println(subtract);
        //-1.958235124123232415534

        BigDecimal a = new BigDecimal("10");
        BigDecimal b = new BigDecimal("2");
        BigDecimal divide = a.divide(b);
        System.out.println(divide);
        //5

        //当不能整除时,需要声明小数点后保留多少位,以及取舍模式
        BigDecimal c = new BigDecimal("3");
        BigDecimal divide1 = a.divide(c, 10, BigDecimal.ROUND_HALF_DOWN);
        //10:保留10位小数
        System.out.println(divide1);
        //3.3333333333
        
        System.out.println(1 == 0.9);
        //false
        System.out.println(1 == 0.9999999999999999999999999999999999);
        //true
        //无限接近,底层补码表示一致
    }
}

时间日期类

Date类

public Date()
public Date(long date)  //把一个long类型的毫秒值转换成一个日期对象
public Date() {
    this(System.currentTimeMillis());
}
public Date(long date) {
    fastTime = date;
}
Date ---- long 的转换	
调用getTime方法

long --- Date 的转换
可以使用构造方法
setTime(long time)
package org.westos.demo1;

import java.util.Date;

/**
 * @author lwj
 * @date 2020/5/3 13:45
 */
public class MyDemo {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date.toString());
        //默认格式:Sun May 03 13:49:17 CST 2020

        Date date1 = new Date(1588475601042L);
        System.out.println(date1);
        //Sun May 03 11:13:21 CST 2020


        //Date --> long
        long time = date.getTime();
        System.out.println(time);
        //1588485370227


        date.setTime(1588475501042L);
        System.out.println(date);
        //Sun May 03 11:11:41 CST 2020
    }
}

SimpleDateFormat

可以把一个日期对象格式化成一个文本字符串 , 也可以把一个日期字符串解析成一个日期对象。

package org.westos.demo1;

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

/**
 * @author lwj
 * @date 2020/5/3 14:00
 */
public class Test {
    public static void main(String[] args) throws ParseException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        
        //日期 --> 字符串
        String s = sdf.format(date);
        System.out.println(s);
        //2020.05.03 14:02:31

        //字符串 --> 日期
        Date parse = sdf.parse(s);
        System.out.println(parse);
        //Sun May 03 14:02:31 CST 2020
    }
}

案例:从出生到现在生活了多少天?

public class Demo2 {
    public static void main(String[] args) throws ParseException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入出生日期:");
        String birthday = sc.nextLine();
        //1998.11.08 10:05:40
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        Date date = sdf.parse(birthday);
        long time = date.getTime();
        long current = System.currentTimeMillis();
        int days = (int)((current - time) / 1000 / 60 / 60 / 24);
        System.out.println(days);
        //7847
    }
}

LocalDateTime

Date里的很多方法都已经弃用了,包括一些构造方法,因为可读性差。

16、Java常用类(Pattern、Matcher)、Math类、Random类、System类、BigDecimal类、时间日期类(Date、SimpleDateFormat、LocalDateT

自Java8开始,增加了一系列表示日期和时间的类,比如LocalDataTime。

package org.westos.demo1;

import java.time.LocalDateTime;

/**
 * @author lwj
 * @date 2020/5/3 14:13
 */
public class Demo {
    public static void main(String[] args) {
        LocalDateTime rightNow = LocalDateTime.now();
        System.out.println("当前时刻:" + rightNow);
        System.out.println("当前年份:" + rightNow.getYear());
        System.out.println("当前月份:" + rightNow.getMonth());
        System.out.println("当前日份:" + rightNow.getDayOfMonth());
        System.out.println("当前时:" + rightNow.getHour());
        System.out.println("当前分:" + rightNow.getMinute());
        System.out.println("当前秒:" + rightNow.getSecond());
        //当前时刻:2020-05-03T14:16:50.287
        //当前年份:2020
        //当前月份:MAY
        //当前日份:3
        //当前时:14
        //当前分:16
        //当前秒:50
    }
}

修改时间

package org.westos.demo1;

import java.time.LocalDateTime;

/**
 * @author lwj
 * @date 2020/5/3 14:18
 */
public class MyTest2 {
    public static void main(String[] args) {
        //构造一个指定年月日的时间
        LocalDateTime localDateTime = LocalDateTime.of(1998, 11, 8, 10, 5, 40);
        System.out.println(localDateTime);
        //1998-11-08T10:05:40

        //修改日期
        localDateTime = localDateTime.minusMinutes(6);
        //减少6min
        localDateTime = localDateTime.plusSeconds(50);
        //增加50s
        localDateTime = localDateTime.withYear(2020);
        //直接修改年份
        localDateTime = localDateTime.withHour(14);
        //直接修改月份

        System.out.println(localDateTime);
        //2020-11-08T14:00:30
    }
}

格式化日期(日期转字符串)

package org.westos.demo1;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author lwj
 * @date 2020/5/3 14:25
 */
public class MyDemo2 {
    public static void main(String[] args) {
        LocalDateTime rightNow = LocalDateTime.now();

        String result1 = rightNow.format(DateTimeFormatter.ISO_DATE);
        String result2 = rightNow.format(DateTimeFormatter.ISO_DATE_TIME);
        String result3 = rightNow.format(DateTimeFormatter.BASIC_ISO_DATE);
        //自定义样式
        String result4 = rightNow.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        System.out.println(result1);
        //2020-05-03
        System.out.println(result2);
        //2020-05-03T14:29:22.994
        System.out.println(result3);
        //20200503
        System.out.println(result4);
        //2020/05/03
    }
}

(字符串转日期)

package org.westos.demo1;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author lwj
 * @date 2020/5/3 14:30
 */
public class Test2 {
    public static void main(String[] args) {
        String s = "2020-05-01 12:13:51";
        //字符串解析为日期
        LocalDateTime localDateTime = LocalDateTime.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(localDateTime);
        //2020-05-01T12:13:51
    }
}

Calendar

package org.westos.demo2;

import java.io.InputStream;
import java.util.Calendar;
import java.util.Scanner;

/**
 * @author lwj
 * @date 2020/5/3 15:40
 */
public class MyTest {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        //抽象类,返回一个Calendar的子类对象,父类引用指向子类对象


        //代替Date类的getYear()/Month()/...方法
        System.out.println(calendar.get(Calendar.YEAR));
        //2020
        System.out.println(calendar.get(Calendar.MONTH) + 1);
        //5
        //0-11 代表 1-12月
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
        //3
        System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
        //24h制
        //15
        System.out.println(calendar.get(Calendar.MINUTE));
        //50
        System.out.println(calendar.get(Calendar.SECOND));
        //4
    }
}
package org.westos.demo2;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import java.util.Calendar;

/**
 * @author lwj
 * @date 2020/5/3 16:00
 */
public class MyDemo {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        //calendar.set(int field, int value); 设置某个日期字段
        calendar.set(2020, Calendar.MAY, 3, 16, 1, 23);
        System.out.println(calendar.get(Calendar.MONTH));
        //4

        //给某个字段增加/减去相应的时间量
        calendar.add(Calendar.YEAR, -1);
        System.out.println(calendar.get(Calendar.YEAR));
        //2019
        calendar.add(Calendar.MONTH, 1);
        System.out.println(calendar.get(Calendar.MONTH));
        //5
    }
}

案例:

键盘录入任意一个年份,获取任意一年的二月有多少天。

package org.westos.demo2;

import java.util.Calendar;
import java.util.Scanner;

/**
 * @author lwj
 * @date 2020/5/3 16:07
 */
public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入年份");
        String year = sc.nextLine();
        String regex = "\\d{4}";
        boolean matches = year.matches(regex);
        if (matches) {
            Calendar calendar = Calendar.getInstance();
            int y = Integer.parseInt(year);
            calendar.set(y, Calendar.MARCH, 1);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
            //2020 29
        }
    }
}

BigInteger

可以让超过long范围内的数据进行运算。

构造方法

public BigInteger(String val)
package org.westos.demo3;

import java.math.BigInteger;

/**
 * @author lwj
 * @date 2020/5/3 16:18
 */
public class MyTest {
    public static void main(String[] args) {
        BigInteger a = new BigInteger(Long.MAX_VALUE + "");
        BigInteger b = new BigInteger(Long.MAX_VALUE + "");
        BigInteger add = a.add(b);
        System.out.println(add);
        //18446744073709551614
    }
}
上一篇:一、求最大公约数


下一篇:大数板子