前言
本期任务:毕向东老师Java视频教程学习笔记(共计25天)
- 原视频链接:黑马程序员_毕向东_Java基础视频教程
- day01:编写HelloWorld程序
- day02:操作符与条件选择语句
- day03:循环语句与函数
- day04:数组
- day07:继承、抽象类与接口
- day08:多态
- day09:异常处理
- day11:多线程
- day12:线程安全与同步机制
- day13:String类
- day14:集合(ArrayList,LinkedList,HashSet)
- day15:集合(TreeSet)和泛型)
- day16:集合(HashMap、TreeMap)
- day17:集合框架的工具类(Arrays、Collections)
- day18:IO流(字符流读写)
- day19:IO流(字节流、转换流读写)
- day20:IO流(File对象)
代码
/*
毕老师用电脑上课
开始思考上课中出现的问题
比如问题是:
电脑蓝屏 -> 重启电脑
电脑冒烟 -> 未知异常,让学生练习,然后安排新老师或者房价
要对问题进行描述,并封装成对象。
可是当冒烟发生后,出现讲课进度无法继续。
出现了讲师的问题,课时计划无法完成
*/
class LanPingException extends Exception {
LanPingException(String message) {
super(message);
}
}
class MaoYanException extends Exception {
MaoYanException(String message) {
super(message);
}
}
class NoPlanException extends Exception {
NoPlanException(String message) {
super(message);
}
}
class Computer {
private int state = 1;
public void run() throws LanPingException, MaoYanException {
if (state == 1)
System.out.println("电脑运行!");
else if (state == 2)
throw new LanPingException("电脑蓝屏了!");
else if (state == 3)
throw new MaoYanException("电脑冒烟了!");
}
public void reset() {
System.out.println("电脑重启!");
}
}
class Teacher {
private String name;
private Computer com = new Computer();
Teacher(String name) {
this.name = name;
}
public void prelect() throws NoPlanException {
try {
com.run();
System.out.println("上课!");
} catch (LanPingException e) {
System.out.println(e.toString());
com.reset();
System.out.println("继续上课!");
} catch (MaoYanException e) {
System.out.println(e.toString());
test();
throw new NoPlanException("课时计划无法继续!");
}
}
public void test() {
System.out.println("做练习");
}
}
public class ExceptionTest {
public static void main(String[] args) {
Teacher t = new Teacher("毕老师");
try {
t.prelect();
} catch (NoPlanException e) {
System.out.println(e.toString());
System.out.println("联系学校换老师或者换电脑!");
}
}
}
/*
有一个长方形和圆形
都可以获取面积,对于面积,如果出现非法值,视为获取面积出现问题
问题通过异常来表示。
现有对这个程序进行基本设计
*/
class NoValueException extends RuntimeException {
NoValueException(String message) {
super(message);
}
}
interface Shape {
void getArea();
}
class Rectangle implements Shape {
private int length, width;
Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public void getArea() throws NoValueException {
if (length <= 0 || width <= 0) {
throw new NoValueException("长方形的长和宽均要大于0");
}
System.out.println(length * width);
}
}
class Circle implements Shape {
private int radius;
public final static double PI = 3.14;
Circle(int radius) {
this.radius = radius;
}
public void getArea() throws NoValueException {
if (radius <= 0) {
throw new NoValueException("圆形的半径要大于0");
}
System.out.println(PI * radius * radius);
}
}
public class ExceptionTest1 {
public static void main(String[] args) {
Rectangle rec = new Rectangle(3, 4);
// Rectangle rec = new Rectangle(-3, 4);
rec.getArea();
Circle c = new Circle(10);
// Circle c = new Circle(-10);
c.getArea();
}
}