带自定义异常类的时钟


import java.text.DecimalFormat;

public class Exec {
public static void main(String[] args) {
Clock c1 = null;
try {
c1 = new Clock(18, 4, 14);
} catch (Exception e) {
e.printStackTrace();
c1 = new Clock();
}

System.out.println(c1.toString());
}
}

class Clock {
public Clock() {
this.hourse = 0;
this.minute = 0;
this.second = 0;
}

public Clock(int hourse, int minute, int second) {
setHourse(hourse);
setMinute(minute);
setSecond(second);
}

public int getHourse() {
return hourse;
}

public void setHourse(int hourse) {
if (hourse >= 0 && hourse <= 23)
this.hourse = hourse;
else
throw new ClockFormatException();
}

public int getMinute() {
return minute;
}

public void setMinute(int minute) {
if (minute >= 0 && minute <= 59)
this.minute = minute;
else
throw new ClockFormatException();
}

public int getSecond() {
return second;
}

public void setSecond(int second) {
if (second >= 0 && second <= 59)
this.second = second;
else
throw new ClockFormatException();
}

@Override
public String toString() {
DecimalFormat df = new DecimalFormat("00");
return (hourse < 12 ? "上午 " : "下午 ") + df.format(hourse) + ":"
+ df.format(minute) + ":" + df.format(second);
}

private int hourse;
private int minute;
private int second;
}

class ClockFormatException extends RuntimeException {

private static final long serialVersionUID = -6387238486450310840L;

public ClockFormatException() {
super("时钟转换出错,时钟将被初始化。");
}

public ClockFormatException(final String s) {
super(s);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值