[英]How can I change my program to allow user input to take the time?
Im struggling on the project I set myself. 我在为自己设定的项目上挣扎。 I want the user to be able to input the time, but it needs to be legal (ie if the time is 9:15 and they add 4 hours, it must be 01:15 Please help! 我希望用户能够输入时间,但是它必须是合法的(即如果时间是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;
}
}
Your problem lies here: 您的问题出在这里:
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;
}
You also need the check after all the addition whether the hh
variable is more than 12. an if it is more than 12 deduct 12. So the corrected format would be: 在所有加法之后,还需要检查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.
}
Here instead of checking whether the sum of this.mm
and mm
is greater than 59. We simply add the mm
to this.mm
and then add the integer division result of this.mm / 60
to hh
. 在这里,无需检查this.mm
和mm
的总和是否大于59。我们只需将mm
添加到this.mm
,然后将this.mm / 60
的整数除法结果添加到hh
。 Also set the remainder of this integer division to this.mm
. 还要将此整数除法的余数设置为this.mm
We repeat the same thing with hh
to store only the remainder of the integer division of this.hh
and 12 to give the output in the 12 hour format. 我们用hh
重复同一件事,只存储this.hh
和12的整数除法的余数,以12小时格式给出输出。
This should take care of your problem. 这应该解决您的问题。
I would suggest using the mod operator. 我建议使用mod运算符。 When the user adds 4 hours. 当用户添加4个小时时。 Use an if statement. 使用if语句。 If the new hour is greater than 12, then mod the new hour to get the correct time. 如果新小时大于12,则修改新小时以获得正确的时间。
ie 即
9:15 + 4 hours => 13:15
13 % 12 => 1
New time = 1:15
You might want to use the LocalDateTime API (added in Java 8). 您可能要使用LocalDateTime API (Java 8中已添加)。
LocalDateTime now = LocalDateTime.now();
LocalDateTime twoHoursFromNow = now.plusHours(2);
Getting user input of time requires parsing: 获取时间的用户输入需要解析:
LocalDateTime inputTime = LocalDateTime.parse("2015-07-13T10:00:00");
LocalDateTime twoHoursFromInputTime = inputTime.plusHours(2);
This question may be a duplicate of Adding n hours to a date in Java? 这个问题可能与在Java中向日期添加n小时重复吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.