JAVA学习历程记录(二)
Date类
Date date = new Date();
DateFormat
实现字符串与date对象的相互转换
y年 M月 d日 H时 m分 s秒
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
parse
将String类型转换成date,但是String要符合格式
String str = "20200814";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = dateFormat.parse(str);
System.out.println(date);
format
将date对象转换成String
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String str = dateFormat.format(date);
System.out.println(str);
日历类
常用API
Calendar c = Calendar.getInstance(); //创建日历
c.get(Calendar.DAY_OF_MONTH) //获得几号
c.get(Calendar.DAY_OF_WEEK) //获得周几
c.get(Calendar.YEAR) //获得几几年
c.get(Calendar.HOUR) //获得时
c.get(Calendar.MINUTE) //获得分
c.set(Calendar.Year,2018)
c.set(Calendar.MONTH ,3) //设置日历时间
练习题
上课时间为每个月前三周周一到周五上午九点到下午五点,如果输入时间在上课时间九点之前,输出未开始上课,若在下午五点之后,输出放学,若输入时间在休息日,输出今天休息
public class DatePratice{
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhh");
Date date = sdf.parse(str);
Calendar c = Calendar.getInstance();
c.setTime(date); //这里传递date
int week = c.get(Calendar.WEEK_OF_MONTH);
int wed = c.get(Calendar.DAY_OF_WEEK);
int time = c.get(Calendar.HOUR_OF_DAY);
if (week<4){
if (wed>1&&wed<5){
if (time>9&&time<17){
System.out.println("上课ing");
}else if (time<=9){
System.out.println("未开始上课");
}
else if (time>=17){
System.out.println("放学了");
}
}
}
else {
System.out.println("休息日");
}}}
异常Exception
java.lang.Throwable是所有Exception和Error的父类
异常分类
编译期异常:需要在编译期间处理
运行时异常:在编译期间不会出现,运行时才会出现的异常
throw和throws
throw:向外抛异常的具体对象
throws:在方法名后面使用,抛出的是异常的类名,如果有多个异常,使用‘,’隔开,或者抛出异常的共同父类
throw new IllegalArgumentException();
public String demo() throws PathNotFoundException,FileFormatException{}
public String demo() throws Exception{}
try…catch
try{
可能出现异常的代码;}
catch(捕获的异常名 变量名){
处理异常的代码;
}
自定义异常
自定义异常类需要继承一个异常,提供有参和无参的构造方法,并在有参构造方法中调用父类的有参构造。
class Demo extends Exception{
public Demo(){}
public Demo(String m){
super(m);
}}
异常的处理方式
若异常的处理方式不同,那么只能使用一个个的catch去处理
若异常的处理方式相同,那么可以使用共同的父类去捕获异常
如果有部分异常的处理方式相同,那么使用分组 捕获,用‘|“隔开
如果有多个异常,那么应该先捕获子类的异常,再捕获父类的异常
异常对方法重写和重载的影响
异常不影响重载
在方法重写时,子类抛出的编译时异常不能超过父类对应方法的编译时范围异常
运行时异常对重写没有影响
finally
无论是否有异常,里面的代码都需要执行
练习题
求两个数的平均数,要求自定义异常类OverRange类,在输入的数大于100小于0时抛出错误,且控制台输出“计算完毕”
public class Average {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
try {
System.out.println(method(a, b));
} catch (OverRange overRange) {
overRange.printStackTrace();
}
finally {
System.out.println("计算完毕");
}
}
public static int method(int a,int b) throws OverRange {
if (a < 0 || a > 99)
throw new OverRange("a超出范围");
if (b < 0 || b > 99)
throw new OverRange("b超出范围");
return (a+b)/2;
}
}
public class OverRange extends Exception{
public OverRange(){
}
public OverRange(String m){
super(m);
}
}