前言
本期任務:畢向東老師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();
}
}