0

我想在每次设置提前分钟时获取时间值,如果分钟为六十,则必须自动添加一小时,然后分钟为零。这是我在课堂上的代码。

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;
  }
}

我的代码中缺少什么,因为它显示错误?

4

2 回答 2

2

它相对简单。

添加advanceminutes,如果minutes大于 59,除以minutes60,这将给出已开始添加的小时数。接下来你修改minutes60 以获得剩余分钟数......

public void advance(int aminutes) {
    minutes = minutes + aminutes;
    if (minutes > 59) {
        int moreHours = Math.round(minutes / 60);
        minutes = minutes % 60;
        hours += moreHours;
    }
}

现在,问题是。为什么不只使用 aCalendar代替?

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;
    }
}
于 2012-12-18T01:15:35.003 回答
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,它将自动添加到小时字段。

于 2012-12-18T04:39:03.850 回答