例题介绍
>工作者在工作中可能会生病,医生监此病人的状态,如发现工作者生病了就给医治
例题设计
>创建工作者类,封装相应的属性和方法
>创建医生类,封装相应的属性和方法
>创建自定义异常类,当工作者生病的时候就去抛出自定义异常
import java.util.Random; public class Dem02 { public static void main(String[] args) { Worker worker = new Worker(); Doctor doctor = new Doctor(); try { worker.work(); }catch(SickException e){ doctor.cure(worker); if(worker.getStatus().equals("健康")) { System.out.println("恭喜你可以恢复了"); }else { System.out.println("我们尽力了"); } } } } class Worker{ private String status;//定义身体状态 public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } public void work() throws SickException{ Random random = new Random(); int r = random.nextInt(3)+1;//产生随机数1-3 if(r == 1) { //自定义异常 throw new SickException("有病"); }else { System.out.println("身体健康,不需要治疗"); } } } //自定义异常类 class SickException extends Exception{ private static final long serialVersionUID = 1L; private String message; public SickException(String message) { this.message = message; } public String getMessage() { return message; } } class Doctor { public void cure(Worker worker) { Random random = new Random(); int rad = random.nextInt(2)+1;//产生随机数1-2 //为worker设置状态 if(rad == 1) { worker.setStatus("健康"); }else { worker.setStatus("治疗无效"); } } }