我的项目代码中有疑问。
我的项目是
我在任务1(2)和任务2(1)中的问题
如何在我的代码中添加条件?
我的2个课程是:
package date;
public class CTime {
int hour;
int minute;
int second;
public CTime(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
public void setHour(int h) {
hour = h;
}
public int getHour() {
return hour;
}
public void setMinute(int m) {
minute = m;
}
public int getMinute() {
return minute;
}
public void setSecond(int s) {
second = s;
}
public int getSecond() {
return second;
}
public void tick() {
second++;
if (second > 59) {
second = 0;
minute++;
if (minute > 59) {
minute = 0;
hour++;
}
if (hour > 23) {
hour = 0;
}
}
}
public String toString() {
String s = (hour > 9 ? hour : "0" + hour) + ":" + (minute > 9 ? minute : "0" + minute) + ":" + (second > 9 ? second : "0" + second);
return s;
}
}
第二节课:
package date;
public class CDateTime extends CTime {
int day;
int month;
int year;
public CDateTime(int ye, int mo, int d, int h, int m, int s) {
super(h, m, s);
year = ye;
month = mo;
day = d;
}
public void setYear(int ye) {
year = ye;
}
public int getYear() {
return year;
}
public void setMonth(int mo) {
month = mo;
}
public int getMonth() {
return month;
}
public void setDay(int d) {
day = d;
}
public int getDay() {
return day;
}
public void tick() {
second++;
if (second > 59) {
second = 0;
minute++;
if (minute > 59) {
minute = 0;
hour++;
}
}
if (hour > 23) {
hour = 0;
day++;
if (day > 30) {
month++;
day = 1;
if (month > 12) {
year++;
month = 1;
}
}
}
}
public String toString() {
String s = year + "-" + (month > 9 ? month : "0" + month) + "-" + (day > 9 ? day : "0" + day) + " " + (hour > 9 ? hour : "0" + hour) + ":" + (minute > 9 ? minute : "0" + minute) + ":" + (second > 9 ? second : "0" + second);
return s;
}
}
我的测试课程是:
package date;
public class main {
public static void main(String[] args) {
CTime x = new CTime(23,59,59);
CDateTime y = new CDateTime(2015,12,30,23,59,59);
System.out.println(x);
x.tick();
System.out.println(x);
System.out.println(y);
y.tick();
System.out.println(y);
}
}
如何添加条件:( 并感谢您的帮助。
答案 0 :(得分:0)
在您的设置方法中,您可以使用if检查条件。
示例:
public void setHour(int h) {
if(h >= 0 && h <= 23)
hour = h;
else
System.out.println("Invalid hours");
}
同样,您也可以在构造函数中执行此操作。正确的方法是抛出异常,但由于你不能使用它,这应该足够了。