3 回答
TA贡献1790条经验 获得超9个赞
如果您使用java.util.Calendar该类,则可以摆脱手动计算。
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hours); //24 hour format (10PM is 22)
c.set(Calendar.MINUTE, minutes);
c.set(Calendar.SECOND, seconds);
System.out.println(c.get(Calendar.HOUR_OF_DAY)
+ ":" + c.get(Calendar.MINUTE)
+ ":" + c.get(Calendar.SECOND));
输出
Enter the hours: 20
Enter the minutes: 120
Enter the seconds: 1276
22:21:16
TA贡献1836条经验 获得超3个赞
您应该阅读有关整数除法/和余数的信息 %。例如:
int seconds = 150;
System.out.println("minutes: " + seconds / 60); // minutes: 2
System.out.println("seconds: " + seconds % 60); // seconds: 30
试试这个代码以了解它是如何工作的:
int seconds = 123;
int minutes = 120;
int hours = 23;
int days = 10;
minutes += seconds / 60;
seconds %= 60;
hours += minutes / 60;
minutes %= 60;
days += hours / 24;
hours %= 24;
System.out.format("%d days, %02d:%02d:%02d hours\n", days, hours, minutes, seconds);
System.exit(0);
这将打印出所有正确的时间:
11 days, 01:02:03 hours
我将在您的代码中添加一些注释:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the hours: ");
int hours = scanner.nextInt();
System.out.print("Enter the minutes: ");
int minutes = scanner.nextInt();
System.out.print("Enter the seconds: ");
int seconds = scanner.nextInt();
if (seconds >= 0 && seconds <= 60) {
minutes = minutes + 1; // why do you increment minutes here?
if (minutes >= 60) {
hours = hours + 1; // if minutes is 120, then you'd have to add 2 hours
minutes = 00; // if minutes is 61, then you should not set minutes to 0
if (hours >= 24) {
hours = 00; // same here
}
}
}
System.out.println(seconds + ":" + minutes + ":" + hours);
}
TA贡献1821条经验 获得超4个赞
这是到目前为止的解决方案,我想..
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What format 12hr or 24hr? [12,24]");
int clockFormat = scanner.nextInt();
System.out.print("Enter seconds: ");
int seconds = scanner.nextInt();
System.out.print("Enter minutes: ");
int minutes = scanner.nextInt();
System.out.print("Enter hours: ");
int hours = scanner.nextInt();
if (clockFormat == 12)
{
while (hours > 12 || hours < 0)
{
System.out.print("Enter the hours: ");
hours = scanner.nextInt();
}
}
minutes += seconds / 60;
seconds %= 60;
hours += minutes / 60;
minutes %= 60;
System.out.format("%02d:%02d:%02d", hours, minutes, seconds);
scanner.close();
}
}
添加回答
举报