gpt4 book ai didi

Java时间转换

转载 作者:行者123 更新时间:2023-12-01 07:50:13 24 4
gpt4 key购买 nike

Scanner input2 = new Scanner(System.in);
System.out.println("Time to be converted to hh:mm:ss: ");
int time = input2.nextInt();
int hr = 0, min = 0, sec = 0;
if(time >= 3600)
{
hr = time/3600;
time = time%3600;
}
if(time >= 60)
{
time = time%3600;
min = time/60;
}
if (time < 60)
{
sec += time;
}
System.out.println(hr+":"+min+":"+sec);

所以,我的问题是,只要秒大于 3719,分钟和小时就停止递增。

示例:

3719
1:1:59

3720
1:1:0

7325
1:1:0

我还尝试了一种不同的算法,使用减法而不是模

Scanner input2 = new Scanner(System.in);
System.out.println("Time to be converted to hh:mm:ss: ");
int time = input2.nextInt();
int hr = 0, min = 0, sec = 0;
if(time >= 3600)
{
hr ++;
time -=3600;
}
if(time >= 60)
{
time -= 60;
min ++;
}
if (time < 60)
{
sec += time;
}
System.out.println(hr+":"+min+":"+sec);

最佳答案

这是因为您使用 3600 作为 min 的模数:

if (time >= 60) {
min = time / 60;
time = time % 3600;
}

但必须使用60,将其更改为:

public static void main(String[] args) {
Scanner input2 = new Scanner(System.in);
System.out.println("Time to be converted to hh:mm:ss: ");
int time = input2.nextInt();
int hr = 0, min = 0, sec = 0;
if (time >= 3600) {
hr = time / 3600;
time = time % 3600;
}
if (time >= 60) {
min = time / 60;
time = time % 60;
}
if (time < 60) {
sec += time;
}
System.out.println(hr + ":" + min + ":" + sec);
}

它会按照你的预期工作。

在这里查看http://ideone.com/unTQTW

关于Java时间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39185280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com