文章目录
一、包装类
(一)包装类的分类 Wrapper
1.针对八种基本数据类型相应的引用类型——包装类
2.有了类的特点,就可以调用类中的方法。
基本数据类型 | 包装类 |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
(二)包装类和基本数据类型的转换
//演示int <--> Integer 的装箱和拆箱
//jdk5前是手动装箱和拆箱
//手动装箱 int->Integer
int n1 = 100;
Integer integer = new Integer(n1);
Integer integer1 = Integer.valueOf(n1);
//手动拆箱
//Integer -> int
int i = integer.intValue();
//jdk5后,就可以自动装箱和自动拆箱
int n2 = 200;
//自动装箱 int -> Integer
Integer integer2 = n2; //底层使用的是Integer.valueOf(n2)
//自动拆箱 Integer -> int
int n3 = integer2;//底层使用的是integer.intValue()
总结:
装箱就是把基本类型装成包装类
拆箱就是把包装类拆成基本类型
(三)课堂测试题
题目
答案
总结:
Integer和Double都是Object的子类,所以Integer正确。
三元运算符是一个整体,后面的Double(2.0)会提升优先级,所以输出小数点。
(四)包装类型和String类型的相互转换
//包装类(Integer) -> String
Integer i = 100;
//方式一
String str1 = i + "";
//方式二
String str2 = i.toString();
//方式三
String str3 = String.valueOf(i);
System.out.println( (str1 + 1) + " " + str2 + " " +str3);
//String -> 包装类(Integer)
String str4 = "12345";
//方式一
Integer i2 = Integer.parseInt(str4);//自动装箱
//方式二
Integer i3 = new Integer(str4);//构造器
//方式三
Integer i4 = Integer.valueOf(str4);//手动装箱
System.out.println((i2 + 1) + " " + i3 + " " +i4);
结果
1001 100 100
12346 12345 12345
(五)Integer类和Character类的常用方法
System.out.println(Integer.MIN_VALUE);//返回最小值
System.out.println(Integer.MAX_VALUE);//返回最大值
System.out.println(Character.isDigit('a'));//判断是不是数字
System.out.println(Character.isLetter('a'));//判断是不是字母
System.out.println(Character.isUpperCase('a'));//判断是不是大写
System.out.println(Character.isLowerCase('a'));//判断是不是小写
System.out.println(Character.isWhitespace('a'));//判断是不是空格
System.out.println(Character.toUpperCase('A'));//判断是不是大写
System.out.println(Character.toLowerCase('a'));//判断是不是小写
结果
-2147483648
2147483647
false
true
false
true
false
A
a
(六)Integer类面试题1
题目
答案
源码:
总结
只要是new出来的,肯定不是同一个对象
(七)Integer类面试题总结
题目
答案:
FFTFFTT
总结
由示例六、示例七得:只要有一个是基本数据类型,判断的是值是否相同
二、String类
(一)String类的理解和创建对象
final char[] value = {'a', 'b', 'c'};
value[0] = 'H';//可以,没改变value的地址,改变了里面的值
//
char[] v2 = {'t', 'o', 'm'};
value = v2;//不可以,改变了value的地址
(二)创建String对象的两种方式
总结:
equals是比较字符串的内容
最后个s1 == s2 是比较s1 ,s2 是否同一个对象,他们两个都是new出来的,false
(三)字符串的特性
创建了两个对象
创建了三个对象
小结:
(四)String类的常用方法
//1. equals 比较内容是否相同,区分大小写
String str1 = "hello";
String str2 = "hello";
String str3 = "Hello";
System.out.println(str1.equals(str2));//true
System.out.println(str1.equals(str3));//false
//2. equalsIgnoreCase 忽略大小写的判断内容是否相同
System.out.println(str1.equalsIgnoreCase(str3));//true
//3.length 获取字符的个数,字符串的长度
System.out.println("好好学习".length());//4
System.out.println("good".length());//4
System.out.println("\n".length());//1
System.out.println("so lo".length());//5
//4.indexOf 获取字符在字符串对象中第一次出现的索引,索引从0开始,如果找不到,返回-1
String s1 = "wer@terwe$e";
int index1 = s1.indexOf('e');
int index2 = s1.indexOf('o');
System.out.println(index1);//1
System.out.println(index2);//-1
System.out.println(s1.indexOf("we"));//0
System.out.println(s1.indexOf("e$"));//8
//5.lastIndexOf 获取字符在字符串对象中最后一次出现的索引,索引从0开始,如果找不到,返回-1
System.out.println(s1.lastIndexOf('e'));//10
System.out.println(s1.lastIndexOf("e$"));//8
//6.substring 截取指定范围的字串
String name = "hello,张三";
System.out.println(name.substring(6));//从索引6开始截取后面所有的字符//张三
System.out.println(name.substring(0,5));//从索引0开始,截取到索引(5-1)个字符//hello
System.out.println(name.substring(2,5));//llo
//1.toUpperCase转换成大写
String s = "heLLo";
System.out.println(s.toUpperCase());//HELLO
//2.toLowerCase装换成小写
System.out.println(s.toLowerCase());//hello
//3.concat拼接字符串
String s1 = "12";
s1 = s1.concat("345").concat("678").concat("9");
System.out.println(s1);//123456789
//4.replace 替换字符串中的字符
String s2 = "101010101010101010";
String s3 = s2.replace("0","1");//s2.replace() 方法执行后,返回的结果才是替换的
System.out.println(s2);//101010101010101010
System.out.println(s3);//111111111111111111
//5.split 分割字符串,对于某些分割字符,我们需要 转义 比如| \\
String p = "123,456,789";
String[] split = p.split(",");
for (int i = 0; i < split.length; i++) {
System.out.print(split[i] + "-");//123-456-789-
}
String p1 = "E:\\aaa\\bbb";
split = p1.split("\\\\");
for (int i = 0; i < split.length; i++) {
System.out.print(split[i] + "-");//E:-aaa-bbb-
}
//6.toCharArray 转换成字符数组
s = "happy";
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i]);//happy
}
//7.compareTo 比较两个字符串的大小,如果前者大
//则返回正数,后者大,则返回负数,如果相等,放回0
//(1) 如果长度不同,内容同,比较len ,len相同是0
String a = "jac";//len = 3
String b = "jack";//len = 4
System.out.println(a.compareTo(b));//-1
//(2)如果长度同,内容不同,比较ascii码
String aa = "jcck";//c 的 ascii 码是99
String bb = "jack";//a 的 ascii 码是97
System.out.println(aa.compareTo(bb));//2
//8.format 格式字符串
String name = "john";
int age = 10;
double score = 98.3 / 3;
char gender = '男';
String str = "我的名字是%s 年龄是%d 成绩是%.2f 性别是%c";
String info = String.format(str, name,age, score,gender);
System.out.println(info);//我的名字是john 年龄是10 成绩是32.77 性别是男
三、StringBuffer类
(一)String Vs StringBuffer
(二)StringBuffer的构造器
String和StringBuffer的相互转换
// String -> StringBuffer
String str = "hello tom";
//方式一 使用构造器
//注意:返回的才是StringBuffer对象,对str本身没有影响
StringBuffer stringBuffer = new StringBuffer(str);
//方式二 使用的是append方法
StringBuffer stringBuffer1 = new StringBuffer();
stringBuffer1 = stringBuffer1.append(str);
//StringBuffer -> String
StringBuffer stringBuffer2 = new StringBuffer("你好,汤姆");
//方式一 使用StringBuffer提供的 toString方法
String s = stringBuffer2.toString();
//方式二 使用构造器来搞定
String s1 = new String(stringBuffer2);
(三)StringBuffer类常见方法
StringBuffer s = new StringBuffer("hello");
//增
s.append(",");//"hello,"
s.append("张三丰");//”hello,张三丰“
s.append("赵敏").append(100).append(true).append(10.3);//hello,张三丰赵敏100true10.3
System.out.println(s);//hello,张三丰赵敏100true10.3
//删
//删除索引为>=start && < end 处的字符
s.delete(11,14);//删除11~14的字符 [11,14)
System.out.println(s);hello,张三丰赵敏true10.3
//改
s.replace(9,11, "周自若");//改 [9,11)
System.out.println(s);//hello,张三丰周自若true10.3
//查
//查找指定的字串在字符串第一次出现的索引,如果找不到返回-1
int indexOf = s.indexOf("张三丰");
System.out.println(indexOf);//6
//插
s.insert(9,"赵敏");
System.out.println(s);//hello,张三丰赵敏周自若true10.3
//长度
System.out.println(s.length());//2
(四)StringBuffer类测试题
String str = null;
StringBuffer sb = new StringBuffer();
sb.append(str);//需要看源码,底层调用的是AbstractStringBuilder 的appendNull,里面是‘n’,'u','l','l'
System.out.println(sb.length());//4
System.out.println(sb);//null
//看底层源码 super(str.length() + 16); str 是null
//会抛出NullPointException
StringBuffer sb1 = new StringBuffer(str);//这里str是null,不是“null"
System.out.println(sb1);
题目
String price = "1231423564.59";
StringBuffer sb = new StringBuffer(price);//String -> StringBuffer
//先完成一个最简单的实现123564.59
//找到小数点的索引,然后在该位置的前三位插入即可
for (int i = sb.lastIndexOf(".") - 3; i >0; i -= 3) {
sb.insert(i, ",");
}
System.out.println(sb);
四、StringBuilder
(一)基本介绍
(二)String、StringBuffer和StringBuilder的比较
效率:String < StringBuffer < StringBuilder
//---------------------StringBuffer-----------------------
long startTime = 0L;
long endTime = 0L;
StringBuffer buffer = new StringBuffer("");
startTime = System.currentTimeMillis();
for( int i = 0; i < 80000; i++) {//StringBuffer 拼接 20000次
buffer.append((i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer的执行时间;" + (endTime - startTime));
//----------------StringBuilder----------------------
StringBuilder builder = new StringBuilder("");
startTime = System.currentTimeMillis();
for( int i = 0; i < 80000; i++) {//StringBuilder 拼接 20000次
builder.append((i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuilder的执行时间;" + (endTime - startTime));
//-------------String-------------------------
String text = "";
startTime = System.currentTimeMillis();
for( int i = 0; i < 80000; i++) {//String 拼接 20000次
text = text + i;
}
endTime = System.currentTimeMillis();
System.out.println("String的执行时间;" + (endTime - startTime));
StringBuffer的执行时间;6
StringBuilder的执行时间;4
String的执行时间;5411
五、Math类
(一)基本介绍
Math类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
//看看Math常用的方法(静态方法)
//1.abs 绝对值
int abs = Math.abs(-9);
System.out.println(abs);//9
//2.pow 求幂
double pow = Math.pow(2, 4);//2的4次方
System.out.println(pow);//16.0
//3.ceil 向上取整,返回 >= 该参数的最小整数
double ceil = Math.ceil(-3.001);
double ceil1 = Math.ceil(3.001);
System.out.println(ceil);//-3.0
System.out.println(ceil1);//4.0
//4.floor 向下取整,返回 <= 该参数的最大整数
double floor = Math.floor(-4.999);
double floor1 = Math.floor(4.999);
System.out.println(floor);//-5.0
System.out.println(floor1);//4.o
//5.round 四舍五入
long round = Math.round(5.51);
long round1 = Math.round(-5.51);
System.out.println(round);//6
System.out.println(round1);//-6
//6.sqrt 求开方
double sqrt = Math.sqrt(9.0);
double sqrt1 = Math.sqrt(-9.0);
System.out.println(sqrt);//3.0
System.out.println(sqrt1);//NaN
//7.random 求随机数
//random 返回的是(0 <= x < 1)之间的随机小数
//思考,请写出获取 a-b 之间的一个随机整数,a,b均为整数, 比如a=2,b=7
//---------------------------
//公式 (int)(a+Math.random()*(b-a+1))
// = (int)(2+Math.random()*6)
//(Math.random()*6 返回的是 0 <= x <6
//(2+Math.random()*6) 返回的是 2 <= x < 8
//(int)(2+Math.random()*6) 返回的是 int取整 2 <= x <= 7
for (int i = 0; i < 10; i++) {
System.out.print((int)(2 + Math.random()*(7-2+1)) + ",");//7,2,2,2,3,6,5,7,3,3,
}
//max,min 返回最大值和最小值
int max = Math.max(33,22);
int min = Math.min(333,222);
System.out.println("max" + max);//max33
System.out.println("min" + min);//mix222
六、Arrays类
> Integer[] integers = {1, 20, 90};
//直接使用Arrays.toString方法,显示数组
System.out.println(Arrays.toString(integers));//[1, 20, 90]
//演示sort方法的使用
public static void main(String[] args) {
int[] arr = {1, -1, 8, 0, 20};
//bubble01(arr);
bubble02(arr, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
int i1 = (Integer) o1;
int i2 = (Integer) o2;
return i1 - i2; //return i2 - i1;这两种方式取决从大到小还是从小到大排序
}
});
System.out.println("====定制排序后的情况=====");
System.out.println(Arrays.toString(arr));
}
//使用冒泡完成排序
public static void bubble01(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr.length - 1 - i; j++) {
//从小到大
if(arr[j] > arr[j + 1]) {
temp =arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
//结合冒泡 + 定制
public static void bubble02(int[] arr, Comparator c) {
int temp = 0;
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr.length - 1 - i; j++) {
//数组排序由 c.compare(arr[j], arr[j + 1]) 返回的值决定
if(c.compare(arr[j], arr[j + 1]) > 0) {
temp =arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
定制排序后的情况=
[-1, 0, 1, 8, 20]
Integer[] arr = {1, 2, 33, 134, 1434};
//binarySearch 通过二分搜索法进行查找,要求必须排好
//1.使用 binarySearch 二叉查找
//2.要去该数组是有序的,如果该数组是无序的,不能使用binarySearch
//3.如果数组中不存在该元素,就返回 return - (low + 1); //key not found
int index = Arrays.binarySearch(arr, 1);
int index1 = Arrays.binarySearch(arr, 134);
int index2 = Arrays.binarySearch(arr, -22);
int index3 = Arrays.binarySearch(arr, 44);
System.out.println("index=" + index);//index=0
System.out.println("index1=" + index1);//index1=3
System.out.println("index2=" + index2);//index2=-1//负数找不到返回-1
System.out.println("index3=" + index3);//index3=-4 //{1, 2, 33, 44, 134, 1434};//return - (low + 1)
//4.copyOf 数组元素的复制
//从 arr 数组中, 拷贝arr.length个元素到 newArray数组中
Integer[] newArr = Arrays.copyOf(arr, arr.length);
Integer[] newArr1 = Arrays.copyOf(arr, arr.length -1);
Integer[] newArr2 = Arrays.copyOf(arr, arr.length + 1);
System.out.println(Arrays.toString(newArr));//[1, 2, 33, 134, 1434]
System.out.println(Arrays.toString(newArr1));//[1, 2, 33, 134]
System.out.println(Arrays.toString(newArr2));//[1, 2, 33, 134, 1434, null]
//5. ill 数组元素的填充
Integer[] num = new Integer[]{9, 3, 2};
//使用 99 去填充num数组,可以理解成是替换原来的元素
Arrays.fill(num, 99);
System.out.println(Arrays.toString(num));//[99, 99, 99]
//6. equals 比较两个数组元素内容是否完全一致
//如果 arr 和 arr2 数组的元素一样,则true
Integer[] arr2 = {1, 2, 33, 134, 1434};
boolean equals = Arrays.equals(arr, arr2);
System.out.println(equals);//true
//7. asList 将一组值,转成list
//1.asList方法,会将(2, 3, 4, 5, 6, 1) 数据转成一个List集合
//2.返回的 asList 编译类型 List(接口)
//3. asList 运行类型 java.util.Arrays#ArrayList, 是Arrays类型
// 静态内部类, private static class ArrayList<E> extends AbstractList<E>
// implements RandomAccess, java.io.Serializale
List asList = Arrays.asList(2, 3, 4, 5, 6, 1);
System.out.println(asList);//[2, 3, 4, 5, 6, 1]
System.out.println("asList的运行类型" + asList.getClass());//asList的运行类型class java.util.Arrays$ArrayList
这里是引用
package com.hspedu.wrapper.stringbuilder;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class StringBuilder01 {
public static void main(String[] args) {
Book[] books = new Book[4];
books[0] = new Book("红楼梦", 100);
books[1] = new Book("金瓶梅新", 90);
books[2] = new Book("青年文摘20年", 5);
books[3] = new Book("java从入门到放弃~", 300);
//(1)price 从大到小
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Book book1 = (Book) o1;
Book book2 = (Book) o2;
double priceVal = book2.getPrice() - book1.getPrice();
if(priceVal > 0) {
return 1;
} else if (priceVal < 0) {
return -1;
} else {
return 0;
}
}
});
System.out.println(Arrays.toString(books));//[Book{name='java从入门到放弃~', price=300.0}, Book{name='红楼梦', price=100.0}, Book{name='金瓶梅新', price=90.0}, Book{name='青年文摘20年', price=5.0}]
//(2)price 从小到大 改下-1 和 1
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Book book1 = (Book) o1;
Book book2 = (Book) o2;
double priceVal = book2.getPrice() - book1.getPrice();
if(priceVal > 0) {
return -1;
} else if (priceVal < 0) {
return 11;
} else {
return 0;
}
}
});
System.out.println(Arrays.toString(books));//[Book{name='青年文摘20年', price=5.0}, Book{name='金瓶梅新', price=90.0}, Book{name='红楼梦', price=100.0}, Book{name='java从入门到放弃~', price=300.0}]
//(3)按照书名长度小到大
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Book book1 = (Book) o1;
Book book2 = (Book) o2;
return book1.getName().length() - book2.getName().length();
}
});
System.out.println(Arrays.toString(books));//[Book{name='红楼梦', price=100.0}, Book{name='金瓶梅新', price=90.0}, Book{name='青年文摘20年', price=5.0}, Book{name='java从入门到放弃~', price=300.0}]
}
}
class Book {
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Book(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
七、System类
//exit 退出当前程序
System.out.println("ok1");
//1.exit(0) 表示程序退出
//2. 0 表示一个状态,正常的状态
//System.exit(0);
System.out.println("ok2");//运行到这,输出ok1,ok2不执行
//arraycopy : 复制数组元素,比较适合底层调用
//一般使用Arrays.copyOf完成复制数组
int[] src = {1,2,3};
int[] dest = new int[3];// dest 当前是 {0,0,0}
//1.主要的五个参数的含义
// 源数组
//2. * @ param src the source array.
// srcPos:从源数组的哪个索引位置开始拷贝
// * @ param srcPos starting position in the source array.
// dest:目标数组,即把源数组的数据拷贝到哪个数组
// * @ param dest the destination array.
// destPos:把源数组的数据拷贝到目标数组的哪个索引
// * @ param destPos starting position in the destination data.
// length:从源数组拷贝多少个数据到目标数组
// * @ param length the number of array elements to be copied.
System.arraycopy(src, 0, dest ,0, 3);//dest=[1, 2, 3](src, 0, dest ,0, src.length)
System.arraycopy(src, 0, dest ,1, 2);//dest=[0, 1, 2]
System.arraycopy(src, 1, dest ,1, 2);//dest=[0, 2, 3]
System.out.println("dest=" + Arrays.toString(dest));
//currentTimeMillens:返回当前时间距离1970-1-1 的毫秒数
System.out.println(System.currentTimeMillis());//1648178408371
八、BigInteger和BigDecimal类
(一)BigInteger和BigDecimal介绍
(二)大数处理方案
//整数
long l = 3421414341342455l;
System.out.println(l);//3421414341342455
BigInteger bigInteger = new BigInteger(("452359829809094572093455"));
BigInteger bigInteger1 = new BigInteger(("100"));
System.out.println(bigInteger);//452359829809094572093455
//add加 subtract减 multiply乘 divide除
BigInteger add = bigInteger.add(bigInteger1);
System.out.println(add);//452359829809094572093555
//小数
double d = 34.344444422d;
System.out.println(d);//34.344444422
BigDecimal bigDecimal = new BigDecimal("34.342222222222222222222222222");
System.out.println(bigDecimal);//34.342222222222222222222222222
//加减乘除
BigDecimal bigDecimal1 = new BigDecimal(("2"));
//除 可能抛出异常ArithmeticException 除不尽
//调用divide 方法时,指定精度即可,BigDecimal.ROUND_CEILING
//如果无限循环小数,就会保留 分子 的精度
System.out.println(bigDecimal.divide(bigDecimal1, BigDecimal.ROUND_CEILING));//17.171111111111111111111111111
九、Date类
(一)第一代日期类
//这里的Date类 是在java.util包
//这种格式是国外的格式
Date d1 = new Date();//获取当前系统时间
System.out.println("当前日期=" + d1);//当前日期=Fri Mar 25 18:47:45 CST 2022
//通过指定的毫秒数得到时间
Date d2 = new Date(42455644);
System.out.println("d2=" + d2);//d2=Thu Jan 01 19:47:35 CST 1970
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");
String format = sdf.format(d1);
System.out.println("当前时间" + format);//当前时间2022年03月25日 06:54:50 星期五
//把格式化的字符串转成对应的字符串
String s = "1996年01月01日 10:30:43 星期一";
Date parse = sdf.parse(s);//抛出异常 throws ParseException
System.out.println("parse=" + sdf.format(parse));//parse=1996年01月01日 10:30:43 星期一
(二)第二代日期类
代码
//1.Calendar是一个抽象类,并且构造器是private
//2.可以通过 getInstance()来获取实例
//3.提供大量的方法和字段提供给程序员
Calendar c = Calendar.getInstance();//创建日历类对象
System.out.println(c);//java.util.GregorianCalendar[time=1648278097572,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=29,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=2,WEEK_OF_YEAR=13,WEEK_OF_MONTH=4,DAY_OF_MONTH=26,DAY_OF_YEAR=85,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=1,SECOND=37,MILLISECOND=572,ZONE_OFFSET=28800000,DST_OFFSET=0]
//2.获取日历对象的某个日历字段
System.out.println("年:" + c.get(Calendar.YEAR));//年:2022
System.out.println("月:" + c.get(Calendar.MONTH) + 1);//月:21//从零开始算,要加一
System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH));//日:26
System.out.println("时:" + c.get(Calendar.HOUR));//时:3//改成24小时,Calendar.HOUR_OF_DAY
System.out.println("分:" + c.get(Calendar.MINUTE));//分:8
System.out.println("秒:" + c.get(Calendar.SECOND));//秒:15
(三)第三代日期类
代码
//第三代日期
//1.使用now() 返回表示当前时间的对象
LocalDateTime ldt = LocalDateTime.now();//LocalDate.now()//LocalTime.now();
System.out.println(ldt);//2022-03-26T15:24:47.049
System.out.println("年=" + ldt.getYear());//年=2022
System.out.println("月=" + ldt.getMonth());//月=MARCH
System.out.println("月=" + ldt.getMonthValue());//月=3
System.out.println("时=" + ldt.getHour());//时=15
System.out.println("分=" + ldt.getMinute());//分=28
System.out.println("秒=" + ldt.getSecond());//秒=11
LocalDate now = LocalDate.now();//可以获取年月日
System.out.println(now);//2022-03-26
LocalTime now1 = LocalTime.now();//可以获取时分秒
System.out.println(now1);//15:31:29.740
代码
LocalDateTime ldt = LocalDateTime.now();//LocalDate.now()//LocalTime.now();
//2.使用DateTimeFormatter 对象来进行格式化
//创建DateTimeFormatter对象
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = dateTimeFormatter.format(ldt);
System.out.println("格式化的日期 " + format);//格式化的日期 2022年03月26日 15时43分01秒
//1.通过静态方法 now() 获取表示当前时间戳的对象
Instant now = Instant.now();
System.out.println(now);//2022-03-26T11:07:37.429Z
//2.通过 from 可以把Instant 转成Date
Date date = Date.from(now);
System.out.println(date);//Sat Mar 26 19:07:37 CST 2022
//3.通过 date的toInstant()可以把date 转成Instant对象
Instant instant = date.toInstant();
System.out.println(instant);//2022-03-26T11:07:37.429Z
//提供plus 和minus 方法可以对当前时间进行加减
//看看890天后,是什么时候,把年月日-时分秒打印
LocalDateTime ldt = LocalDateTime.now();//LocalDate.now()//LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = ldt.plusDays(890);
System.out.println(dateTimeFormatter.format(localDateTime));//2024-09-01 19:14:12
//看看3456 分钟前是什么时候, 看年月日-时分秒打印
LocalDateTime localDateTime1 = ldt.minusMinutes(3456);
System.out.println(dateTimeFormatter.format(localDateTime1));//2022-03-24 09:42:31
十、本章作业
(一)String翻转
public static void main(String[] args) {
//测试
String str = "abcdef";
System.out.println("交换前" + str);//交换前abcdef
try {
str = reverse(str, 1, 24);
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
System.out.println("交换后" + str);//交换后aedcbf
}
public static String reverse(String str, int start, int end) {
//编程技巧分享
//(1) 写出正确的情况
//(2) 然后取反即可
if(!(str != null && start >= 0 && end > start && end <str.length())) {
throw new RuntimeException("参数不正确");
}
char[] chars = str.toCharArray();
char temp = ' ';// 交换辅助变量
for(int i = start, j = end; i < j; i++, j--) {
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
//使用chars 重新构建一个String 返回即可
return new String(chars);
}
(二)注册处理题
public static void main(String[] args) {
String name = "jack";
String pwd = "123456";
String email = "jack@sohu.com";
try {
userRegister(name,pwd,email);
System.out.println("恭喜你,注册成功~");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void userRegister(String name, String pwd, String email) {
if(!(name != null && pwd != null && email != null)) {
throw new RuntimeException("常数不能为空");
}
//第一关
int userLength = name.length();
if (!(userLength >= 2 && userLength <= 4)) {
throw new RuntimeException("用户名长度为(2-4)");
}
//第二关
if (!(pwd.length() == 6 && isDigital(pwd))) {
throw new RuntimeException("密码的长度为6,要求全部是数字");
}
//第三关
int i = email.indexOf('@');
int j = email.indexOf('.');
if (!(i > 0 && j > i)) {
throw new RuntimeException("邮箱中包含@ 和. 并且@在.的前面");
}
}
//单独的写一个方法,判断密码是否全部是数字字符 boolean
public static boolean isDigital(String str) {
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] < '0' || chars[i] > '9') {//判断ascii码值
return false;
}
}
return true;
}
(三)字符串统计
public static void main(String[] args) {
String name = "Han Shun Ping";
printName(name);
}
public static void printName(String str) {
if(str == null) {
System.out.println("str 不能为空");
return;
}
String[] names = str.split(" ");
if(names.length != 3) {
System.out.println("输入的字符串格式不正确");
return;
}
String format = String.format("%s,%s .%c", names[2], names[0], names[1].toUpperCase().charAt(0));
System.out.println(format);//Ping,Han .S
}
(四)String内存分布
public static void main(String[] args) {
String str = "1234 abc HH";
countStr(str);
}
public static void countStr(String str) {
if(str == null) {
System.out.println("输入不能为null");
return;
}
int strLen = str.length();
int numCount = 0;
int lowerCount = 0;
int upperCount = 0;
int otherCount = 0;
for (int i = 0; i < strLen; i++) {
if(str.charAt(i) >= '0' && str.charAt(i) <= '9') {
numCount++;
} else if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
lowerCount++;
} else if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
upperCount++;
} else {
otherCount++;
}
}
System.out.println("数字有 " + numCount);//数字有 4
System.out.println("小写字母有 " + lowerCount);//小写字母有 3
System.out.println("大写字母有 " + upperCount);//大写字母有 2
System.out.println("其他字母有 " + otherCount);//其他字母有 2
}
总结:
第二个输出:equals是比较字符串的内容,不适合比较对象
你的a b是对象,不是字符串