我希望每次设置提前分钟时获得时间值,如果分钟为60分钟,则必须自动添加1小时,然后分钟将为零。 这是我班上的代码。
public class time {
private int hours;
private int minutes;
private String amPm;
public time() {
}
public time(int hours, int minutes, String amPm) {
this.hours = hours;
this.minutes = minutes;
this.amPm = amPm;
}
public void advance(int aminutes){
if(minutes > 0){
minutes = minutes + aminutes;
while(hours < 0){
}
}
}
@Override
public String toString() {
String time = hours + " " + minutes + " " + amPm + ".";
return time;
}
}
我的代码中缺少什么,因为它显示错误?
答案 0 :(得分:2)
这相对简单。
将advance
添加到minutes
,如果minutes
大于59,将minutes
除以60,这将给出已添加的小时数。接下来,您将minutes
修改为60,以获得剩余分钟数...
public void advance(int aminutes) {
minutes = minutes + aminutes;
if (minutes > 59) {
int moreHours = Math.round(minutes / 60);
minutes = minutes % 60;
hours += moreHours;
}
}
现在,问题是。为什么不使用Calendar
代替?
public class Time {
public static void main(String[] args) {
Time time = new Time();
time.advance(90);
System.out.println(time);
}
private Calendar cal;
public Time() {
cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
}
public Time(int hours, int minutes) {
this();
cal.set(Calendar.HOUR, hours);
cal.set(Calendar.MINUTE, minutes);
}
public void advance(int aminutes) {
cal.add(Calendar.MINUTE, aminutes);
}
@Override
public String toString() {
String time = cal.get(Calendar.HOUR_OF_DAY) + " " + cal.get(Calendar.MINUTE);
return time;
}
}
答案 1 :(得分:0)
@MadProgrammer非常正确使用 java.util.Calendar 类。这个类比Date更聪明。
以下是示例代码:
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.HOUR)+" :: "+cal.get(Calendar.MINUTE));
cal.add(Calendar.MINUTE, 80);
System.out.println(cal.get(Calendar.HOUR)+" :: "+cal.get(Calendar.MINUTE));
如果分钟增加超过60,它将自动添加到小时字段。