我正在为自己设定的项目而苦苦挣扎。我希望用户能够输入时间,但它必须是合法的(即,如果时间是 9:15 并且他们添加 4 小时,则它必须是 01:15 请帮忙!
package time;
public class NewTime {
int hh, mm;
public NewTime(int hh, int mm) {
if (hh > 0 && hh < 24 && mm > 0 && mm < 60) {
this.hh = hh;
this.mm = mm;
}
}
public void addTime(int hh, int mm) {
if (mm + this.mm > 59) {
this.hh += mm / 60;
}
this.hh += hh;
this.mm += mm;
}
}
最佳答案
你的问题出在这里:
public void addTime(int hh, int mm) {
if (mm + this.mm > 59) {
this.hh += mm / 60;
}
this.hh += hh; //<--source of problem
this.mm += mm;
}
在所有加法之后还需要检查hh
变量是否大于12。如果大于12则扣除12。所以正确的格式是:
public void addTime(int hh, int mm) {
this.hh += hh;
this.mm += mm;
this.hh += this.mm / 60;
this.mm = this.mm % 60; //This removes the problem where the mm may be 59 and this.mm is 2
this.hh = this.hh % 12; //This solves the problem of hour not getting over 12.
}
这里不检查 this.mm
和 mm
之和是否大于 59。我们只是将 mm
添加到 this.mm
,然后将this.mm/60
的整数除法结果与hh
相加。还要将此整数除法的余数设置为 this.mm
。我们使用 hh
重复同样的操作,仅存储 this.hh
整数除法的余数,并使用 12 给出 12 小时格式的输出。
这应该可以解决您的问题。
关于java - 我怎样才能改变我的程序以允许用户输入花时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31384860/