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);
}
}
带自定义异常类的时钟
最新推荐文章于 2024-10-11 17:30:36 发布