异常---医生给工作者看病
发布日期:2021-06-28 13:57:10 浏览次数:2 分类:技术文章

本文共 1293 字,大约阅读时间需要 4 分钟。

例题介绍

>工作者在工作中可能会生病,医生监此病人的状态,如发现工作者生病了就给医治

例题设计

>创建工作者类,封装相应的属性和方法

>创建医生类,封装相应的属性和方法

>创建自定义异常类,当工作者生病的时候就去抛出自定义异常

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("治疗无效");		}	}}

转载地址:https://blog.csdn.net/wyf2017/article/details/80217386 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:对ArrayList容器中的数据进行排序
下一篇:验证码的生成

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月06日 13时13分22秒