public LocalDateTime withDayOfMonth(int dayofmonth)
直接修改日期(一个月中的第几天)
public LocalDateTime withDayOfYear(int dayOfYear)
直接修改日期(一年中的第几天)
public LocalDateTime withHour(int hour)
直接修改小时
public LocalDateTime withMinute(int minute)
直接修改分钟
public LocalDateTime withSecond(int second)
直接修改秒
示例代码
2.2.9 Period (应用)
方法说明
方法名
说明
public static Period between(开始时间,结束时间)
计算两个“时间"的间隔
public int getYears()
获得这段时间的年数
public int getMonths()
获得此期间的总月数
public int getDays()
获得此期间的天数
public long toTotalMonths()
获取此期间的总月数
示例代码
/**
* 计算两个时间的间隔
*/publicclassJDK8DateDemo9{publicstaticvoidmain(String[] args){//public static Period between(开始时间,结束时间) 计算两个"时间"的间隔LocalDate localDate1 =LocalDate.of(2020,1,1);LocalDate localDate2 =LocalDate.of(2048,12,12);Period period =Period.between(localDate1, localDate2);System.out.println(period);//P28Y11M11D//public int getYears() 获得这段时间的年数System.out.println(period.getYears());//28//public int getMonths() 获得此期间的月数System.out.println(period.getMonths());//11//public int getDays() 获得此期间的天数System.out.println(period.getDays());//11//public long toTotalMonths() 获取此期间的总月数System.out.println(period.toTotalMonths());//347}}
2.2.10 Duration (应用)
方法说明
方法名
说明
public static Durationbetween(开始时间,结束时间
计算两个“时间"的间隔
public long toSeconds()
获得此时间间隔的秒
public int toMillis()
获得此时间间隔的毫秒
public int toNanos()
获得此时间间隔的纳秒
示例代码
/**
* 计算两个时间的间隔
*/publicclassJDK8DateDemo10{publicstaticvoidmain(String[] args){//public static Duration between(开始时间,结束时间) 计算两个“时间"的间隔LocalDateTime localDateTime1 =LocalDateTime.of(2020,1,1,13,14,15);LocalDateTime localDateTime2 =LocalDateTime.of(2020,1,2,11,12,13);Duration duration =Duration.between(localDateTime1, localDateTime2);System.out.println(duration);//PT21H57M58S//public long toSeconds() 获得此时间间隔的秒System.out.println(duration.toSeconds());//79078//public int toMillis() 获得此时间间隔的毫秒System.out.println(duration.toMillis());//79078000//public int toNanos() 获得此时间间隔的纳秒System.out.println(duration.toNanos());//79078000000000}}
publicclassExceptionDemo02{publicstaticvoidmain(String[] args){System.out.println("开始");method();System.out.println("结束");}publicstaticvoidmethod(){try{int[] arr ={1,2,3};System.out.println(arr[3]);//new ArrayIndexOutOfBoundsException();System.out.println("这里能够访问到吗");}catch(ArrayIndexOutOfBoundsException e){//newArrayIndexOutOfBoundsException();// e.printStackTrace();//public String getMessage():返回此 throwable 的详细消息字符串// System.out.println(e.getMessage());//Index 3 out of bounds for length 3//public String toString():返回此可抛出的简短描述// System.out.println(e.toString());//java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3//public void printStackTrace():把异常的错误信息输出在控制台
e.printStackTrace();// java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3// at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18)// at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11)}}}
publicclassStudent{privateString name;privateint age;publicStudent(){}publicStudent(String name,int age){this.name = name;this.age = age;}publicStringgetName(){return name;}publicvoidsetName(String name){this.name = name;}publicintgetAge(){return age;}publicvoidsetAge(int age){if(age >=18&& age <=25){this.age = age;}else{//当年龄不合法时,产生一个异常thrownewRuntimeException("年龄超出了范围");}}@OverridepublicStringtoString(){return"Student{"+"name='"+ name +'\''+", age="+ age +'}';}}
测试类
publicclassExceptionDemo12{publicstaticvoidmain(String[] args){// 键盘录入学生的姓名和年龄,其中年龄为 18 ‐ 25岁,// 超出这个范围是异常数据不能赋值.需要重新录入,一直录到正确为止。Student s =newStudent();Scanner sc =newScanner(System.in);System.out.println("请输入姓名");String name = sc.nextLine();
s.setName(name);while(true){System.out.println("请输入年龄");String ageStr = sc.nextLine();try{int age =Integer.parseInt(ageStr);
s.setAge(age);break;}catch(NumberFormatException e){System.out.println("请输入一个整数");continue;}catch(AgeOutOfBoundsException e){System.out.println(e.toString());System.out.println("请输入一个符合范围的年龄");continue;}/*if(age >= 18 && age <=25){
s.setAge(age);
break;
}else{
System.out.println("请输入符合要求的年龄");
continue;
}*/}System.out.println(s);}}
3.10 自定义异常(应用)
自定义异常概述 当Java中提供的异常不能满足我们的需求时,我们可以自定义异常
实现步骤
定义异常类
写继承关系
提供空参构造
提供带参构造
代码实现
异常类
public class AgeOutOfBoundsException extends RuntimeException {
public AgeOutOfBoundsException() {
}
public AgeOutOfBoundsException(String message) {
super(message);
}
}
学生类
publicclassStudent{privateString name;privateint age;publicStudent(){}publicStudent(String name,int age){this.name = name;this.age = age;}publicStringgetName(){return name;}publicvoidsetName(String name){this.name = name;}publicintgetAge(){return age;}publicvoidsetAge(int age){if(age >=18&& age <=25){this.age = age;}else{//如果Java中提供的异常不能满足我们的需求,我们可以使用自定义的异常thrownewAgeOutOfBoundsException("年龄超出了范围");}}@OverridepublicStringtoString(){return"Student{"+"name='"+ name +'\''+", age="+ age +'}';}}
测试类
publicclassExceptionDemo12{publicstaticvoidmain(String[] args){// 键盘录入学生的姓名和年龄,其中年龄为 18 ‐ 25岁,// 超出这个范围是异常数据不能赋值.需要重新录入,一直录到正确为止。Student s =newStudent();Scanner sc =newScanner(System.in);System.out.println("请输入姓名");String name = sc.nextLine();
s.setName(name);while(true){System.out.println("请输入年龄");String ageStr = sc.nextLine();try{int age =Integer.parseInt(ageStr);
s.setAge(age);break;}catch(NumberFormatException e){System.out.println("请输入一个整数");continue;}catch(AgeOutOfBoundsException e){System.out.println(e.toString());System.out.println("请输入一个符合范围的年龄");continue;}/*if(age >= 18 && age <=25){
s.setAge(age);
break;
}else{
System.out.println("请输入符合要求的年龄");
continue;
}*/}System.out.println(s);}}
4.Optional
4.1获取对象(应用)
Optional概述 可能包含或不包含非null值的容器对象
方法介绍
方法名
说明
static Optional of(T value)
获取一个Optional对象,封装的是非null值的对象
static Optional ofNullable(T value)
获取一个Optional对象,Optional封装的值对象可以是null也可以不是null
示例代码
publicclassOptionalDemo1{publicstaticvoidmain(String[] args){//method1();//public static <T> Optional<T> ofNullable(T value)//获取一个Optional对象,Optional封装的值对象可以是null也可以不是null//Student s = new Student("zhangsan",23);Student s =null;//ofNullable方法,封装的对象可以是null,也可以不是null。Optional<Student> optional =Optional.ofNullable(s);System.out.println(optional);}privatestaticvoidmethod1(){//static <T> Optional<T> of(T value) 获取一个Optional对象,封装的是非null值的对象//Student s = new Student("zhangsan",23);Student s =null;//Optional可以看做是一个容器,里面装了一个引用数据类型的对象。//返回值就是Optional的对象//如果使用of方法,封装的对象如果为空,那么还是会抛出空指针异常Optional<Student> optional1 =Optional.of(s);System.out.println(optional1);}}
4.2常用方法(应用)
方法介绍
方法名
说明
T get()
如果存在值,返回值,否则抛出NoSuchElementException
boolean isPresent()
如果存在值,则返回true,否则为false
示例代码
publicclassOptionalDemo2{publicstaticvoidmain(String[] args){//get() 如果存在值,返回值,否则抛出NoSuchElementException//public boolean isPresent() 判断Optional所封装的对象是否不为空,如果不为空返回true, 否则返回false//Student s = new Student("zhangsan",23);Student s =null;Optional<Student> optional =Optional.ofNullable(s);//如果封装的是一个null,那么通过get方法再次获取会抛出NoSuchElementException。if(optional.isPresent()){Student student = optional.get();System.out.println(student);}else{System.out.println("Optional封装的对象为空");}}}
4.3处理空指针的方法(应用)
方法介绍
方法名
说明
T orElse(T other)
如果不为空,则返回具体的值,否则返回参数中的值
T orElseGet(Supplier<? extends T> supplier)
如果不为空,则返回具体的值,否则返回由括号中函数产生的结果
void ifPresent (Consumer<? super T> action)
如果不为空,则使用该值执行给定的操作,否则不执行任何操作
void ifPresentOrElse(Consumer<? super T>action, Runnable emptyAction)
如果不为空,则使用该值执行给定的操作,否则执行给定的基于空的操作
示例代码
publicclassOptionalDemo3{publicstaticvoidmain(String[] args){//method1();//method2();//method3();//method4();}privatestaticvoidmethod4(){//Student s = new Student("zhangsan",23);Student s =null;Optional<Student> optional =Optional.ofNullable(s);//public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)、//如果不为空,则使用该值执行给定的操作,否则执行给定的基于空的操作。
optional.ifPresentOrElse(student ‐>System.out.println(student),()‐>System.out.println("为空了"));}privatestaticvoidmethod3(){//Student s = new Student("zhangsan",23);Student s =null;Optional<Student> optional =Optional.ofNullable(s);//ifPresent (Consumer<? super T> action)//如果不为空,则使用该值执行给定的操作,否则不执行任何操作
optional.ifPresent(student ‐>System.out.println(student));}privatestaticvoidmethod2(){Student s =newStudent("zhangsan",23);//Student s = null;Optional<Student> optional =Optional.ofNullable(s);//orElseGet(Supplier<? extends T> supplier)//如果不为空,则返回具体的值,否则返回由括号中函数产生的结果Student student = optional.orElseGet(()‐>newStudent("lisi",24));System.out.println(student);}privatestaticvoidmethod1(){//Student s = new Student("zhangsan",23);Student s =null;Optional<Student> optional =Optional.ofNullable(s);//orElse(T other) 如果不为空,则返回具体的值,否则返回参数中的值Student student = optional.orElse(newStudent("lisi",24));System.out.println(student);}}