Java一些新的知识

数学

最大int

通过Integer类名访问最大的int数

System.out.println(Integer.MAX_VALUE);

生成随机数

// 返回 0 - 4之间的一个数
int randNum = (int) (Math.random() * 5);

Math.random() 方法返回0 - 1(不包括1) 之间的一个数, 注意强制转换

也可以用 java.util.Random的nextInt()方法, 这种不需要强转

返回最接近的整数值 rint()

处理位数左边是奇数 => 四舍五入 左边是偶数 => 五舍六入

static double rint(double x)

日期和时间类

Date类

输出当前系统时期和时间

Date date = new Date();
System.out.println(date);

在这里插入图片描述

输出计算自1970年1月1日00:00:00AM以来的毫秒数

Date date = new Date();
System.out.println(date.getTime());

LocalDate类 - 日期

默认格式为 yyyy-MM-DD

now() =>系统默认当前操作系统的默认时区,如需更改, 参见java.time.ZoneDateTime 

getYear() => 年份 

getMonth() =>月份, 英文字符串 

getMouthValue() =>月份, 1-12getDayOfWeek() => 星期, 英文字符串

getDayOfMonthh() => 当月日期

getDayOfYear() =>当前日期
LocalDate date = LocalDate.now();
System.out.println(date);

在这里插入图片描述

LocalTime类

不含时区. 默认格式为 hh:mm:ss:zzz

LocalTime time = LocalTime.now();
System.out.println(time);

在这里插入图片描述

LocalDateTime类 - 同时显示日期和时间

默认格式为yyyy-MM-ddTHH:mm:ss:zzz

Instant 时间戳类

now()返回当前时间点

Duration类 - 计算时间间距

public static void main(String[] args) {
    LocalDateTime from, to;
    final int ans = 77;
    int num;
    Scanner scanner = new Scanner(System.in);
    from = LocalDateTime.now();
    while (true) {
        System.out.println("请猜0-99的数字: ");
        num = scanner.nextInt();
        if (num == ans) {
            System.out.println("恭喜你猜对了!");
            to = LocalDateTime.now();
            break;
        }
        System.out.println("猜错了, 再猜一次");
    }
    Duration dura = Duration.between(from, to);
    System.out.println("所花天数 " + dura.toDays());
    System.out.println("所花小时数 " + dura.toHours());
    System.out.println("所花分钟数 " + dura.toMinutes());
    System.out.println("所花秒数 " + dura.toSeconds());
    System.out.println("所花毫秒数 " + dura.toMillis());
    System.out.println("所花纳秒数 " + dura.toNanos());
}

在这里插入图片描述

字符串类

Character类

方法说明
static boolean isDigit(char ch)是否是数字
static boolean isLetter(char ch)是否是字母
static boolean isISOControl(char ch)是否是ISO控制字符
static boolean isLowerCase(char ch)是否是小写字母
static boolean isSpaceChar(char ch)是否是Unicode额空格符
static char toLowerCase(char ch)将字符变为小写
toString()返回字符的字符串形式,字符串的长度仅为1
static char forDigit(char ch)返回数值n在基底数值的字符, 如果数值不是基底数字的字符则返回空格符
static int digit(char ch, int radix)将字符转换为制定基数的数值, 不能转换则返回-1

String类

参照与副本的差异

 public static void main(String[] args) {
    char[] ch1 = {'绝', '崩', '穹'};
    String s1 = new String();
    String s2 = new String(ch1);
    String s3 = new String(s2);
    s1 = s2;
    System.out.println("s1 = " + s1);
    System.out.println("s2 = " + s2);
    System.out.println("s3 = " + s3);
    System.out.println("s1 == s2吗  " + (s1 == s2));
    System.out.println("s3 == s2吗  " + (s3 == s2));
}

在这里插入图片描述

字符查找

方法说明
int indexOf(int ch)返回第一次出现ch字符的索引位置
int indexOf(int ch, int index)返回从index起第一次出现ch字符的索引位置
int lastIndexOf(int ch)返回最后一次出现ch字符的索引位置
int indexOf(int ch)返回第一次出现ch字符的索引位置
int indexOf(int ch)返回第一次出现ch字符的索引位置

子字符串的查找

方法
int indexOf(String s)
int indexOf(String s, int index)
int lastIndexOf(String s)
int lastIndexOf(String s, int index)
boolean contains(CharSequence s)

截取子字符串或字符

方法说明
char charAt(int index)返回指定索引char字符
String substring(int beginIndex)beginIndex起的新子字符串
void getChars(int srcBgein, int srcEnd, char[] dst, int dstBegin)从srcBegin开始到srcEnd - 1结束字符串复制至dst目标数组dstBegin位置开始
char[] toCharArray()复制一份字符串到字符数组

替换

方法说明
String replace(char oldChar, char newChar)用newChar新字符替换oldChar旧字符
String replace(CharSequence target, CharSequence replacement)将所有target字符串用replacement字符串替代
String trim()删除开头和结尾空格符, 包含制表符和换行符

比较

方法说明
int compareTo(String anotherString)>0 则字符串较大 ==0 则相等
int compareToIgnoreCase(String anotherString)忽略大小写的比较
boolean equals(Object anObject)将字符串内容与对象作比较, 相同则返回true
boolean endsWith(String suffix)检查字符串是否以suffix作为后缀
boolean startsWith(String prefix)检查字符串是否以prefix作为前缀
boolean startsWith(String prefix, int index)检查字符串是否在index下标处以prefix作为前缀

转换

方法说明
static String copyValueOf(char []data)将data字符数组变为字符串
static String copyValueOf(char []data, int index, int count)将data字符数组从index下标开始长度是count的字符转换成字符串
static String ValueOf(boolean b)将boolean值转换成字符串
static String ValueOf(char []data)将data字符数组变成字符串
static String ValueOf(double d)将double值专为字符串
static StringValueOf(long l)将long值转成字符串

split()

public static void main(String[] args) {
    String s = " I love Java";
    String[] words = s.split("\\s");
    System.out.printf("s句子有 %d 个字", words.length);
    for (String word : words) {
        System.out.println(word);
    }
}

在这里插入图片描述

StringBuffer类

String类不会碰上需要处理重新分配内存的问题

这个类在建立对象时不会限定长度, 如果遇上增加字符串长度, Java编译程序会在同一个内存里处理, 不会建立新对象放置修改后的内容

处理缓冲区长度和容量

方法说明
int capacity()返回字符串缓冲区容量
int ensureCapacity(int minimumCapacity)配置缓冲区最小容量, 如果参数 > 目前容量 最后容量是旧容量 * 2 + 2, 如果小于旧容量则不更改
int length()返回字符串缓冲区对象长度
int setLength(int newLength)设置字符串缓冲区对象长度

内容修改

方法说明
StringBuffer append(type data)将任意类型的数据加在原对象后方
StringBuffer append(char []s, int index, int len)将字符数组index位置len长度加在原对象后方
StringBuffer insert(int index, type data)将任意类型的数据加在原对象制定index位置
StringBuffer insert(int index, char[]s, int offset, int len)将字符数组offset位置len长度加在原对象index位置
StringBuffer delete(int start, int end)删除指定字符串区间内容, 前闭后开
StringBuffer deleteCharAt(int index)删除指定index位置的内容
StringBuffer reverse()将字符串前后顺序反转

复制子字符串

void getChars(int srcBegin, int srcEnd, char[]dst, int dstBegin)将字符串从srcBegin索引至srcEnd - 1的子字符串复制到dstBegin索引
public static void main(String[] args) {
    String s = "崩坏星穹铁道";
    StringBuffer bs = new StringBuffer(s);
    char[] ch = {'绝', '区', '零'};
    bs.getChars(2, 5, ch, 0);
    System.out.print("bs: ");
    for (char i : ch)
        System.out.print(i);
}

在这里插入图片描述

正则表达式

String类处理

方法说明
boolean matches(String regex)返回字符串是否符合正则表达式
String replaceAll(String regex, String replacement)将符合正则表达式的字符串全部用另一字符串取代
String replaceFirst(Sting regex, String replacement)将第一个符合正则表达式的字符串全部用另一字符串替代

正则表达式基础

  1. \d 表示0~9的数字字符
public static void main(String[] args) {
    String s = "";
    String pattern = "\\d";
    Scanner scanner = new Scanner(System.in);
    System.out.println("输入任意字符串");
    s = scanner.next();
    if (s.matches(pattern)) {
        System.out.printf("%s : 是 0~9数字\n", s);
    } else {
        System.out.println("不是0~9数字");
    }
}

在这里插入图片描述

  1. 管道 | 同时查找比对多个字符串
pattern ="Mary|Tom"; // 单引号或|旁边不能有空白
正则表达式说明
X?X出现0次或1次
X*X出现0~多次
X+X出现1~多次
X{n}X出现n次
X{n, }X出现n次~多次
X{ , m}X出现0次~m次
X{n, m}X出现n次~m次

正则表达式的特殊字符

字符使用说明
.任何一个字符
\d0~9的整数
\D0~9的整数以外的其他字符
\s空白, 定位, Tab键, 换行, 换页字符
\S除上述以外的其他字符
\w数字, 字母, 下划线, [A-Z, a-z, 0-9_]
\W除上述以外的其他字符

java.util.regex包

Matcher类

方法说明
boolean matches()检查字符串是否符合正则表达式
boolean find()查找与正则表达式相符合的下一个字符串
boolean find(int start)查找从start开始的符合正则表达式的下一个字符串
String group()返回符合的子串行
int start()返回符合的子串行起始索引
int end()返回符合的子串结束始索引
String replaceAll(String replacement)替换符合的所有子字符串
String replaceFirst(String replacement)替换符合的第一个子字符串

Pattern类

方法说明
Static Pattern compile(String regex)编译正则表达式
Matcher matcher(CharSequence input)由输入的字符串建立Matcher对象
String pattern()返回正则表达式模式

示例

比对
public static void main(String[] args) {
	String s = "0952-001-001";
	String pattern = "\\d{4}(-\\d{3}){2}";
	
	// 方法1
	Pattern p = Pattern.compile(pattern); // 编译正则表达式
	Matcher m = p.matcher(s);
	System.out.println("方法1: " + m.matches());
	
	// 方法2
	System.out.println("方法2: " + Pattern.matches(pattern, s));
 }

在这里插入图片描述

public static void main(String[] args) {
    System.out.println(Pattern.matches("[abc]?", "a"));
    System.out.println(Pattern.matches("[abc]?", "ab"));
    System.out.println(Pattern.matches("[abc]+", "ab"));
    System.out.println(Pattern.matches("[abc]*", "ab"));
    System.out.println(Pattern.matches("\\D", "a"));
    System.out.println(Pattern.matches("\\D", "1"));
    System.out.println(Pattern.matches("\\D*", "abc"));
}

在这里插入图片描述

System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "aK2APL"));
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "abc10"));   // 太短
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "abPL0981")); // 太长
System.out.println(Pattern.matches("[23][0-9]{7}", "28229999")); // 
System.out.println(Pattern.matches("[23][0-9]{7}", "93990011")); // 开头错
System.out.println(Pattern.matches("[23][0-9]{7}", "230000")); // 太短
System.out.println(Pattern.matches("[23][0-9]{7}", "230000011")); // 太长

在这里插入图片描述

查找
public static void main(String[] args) {
     String msg = "通过号码 0930-919-919 或者 0952-001-001";
     String pattern = "\\d{4}(-\\d{3}){2}";
     Pattern p = Pattern.compile(pattern);
     Matcher m = p.matcher(msg);
     boolean found = false;

     while (m.find()) {
         System.out.println(m.group() + "字符串找到了起始索引 " + m.start() + "终止索引是" + m.end());
         found = true;
     }

     if (!found) {
         System.out.println("查找失败");
     }

 }
替换
 public static void main(String[] args) {
     String msg = "CIA Mark told CIA Linda that secret USB had given to CIA Peter";
     String pattern = "CIA \\w*";
     String replace = "C*A **";
     Pattern p = Pattern.compile(pattern);
     Matcher m = p.matcher(msg);
     System.out.println(m.replaceFirst(replace));
     System.out.println(m.replaceAll(replace));

 }

在这里插入图片描述

  • 21
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值