怎么解决这个问题? java作业

时间:2015-11-20 03:39:13

标签: java

我有作业

这是我的问题

enter image description here

我的代码是

public class DisplayTime {

    public static void main(String[] args) {        
        int seconds = 290;
        int hour = seconds/60/60;
        int minute = seconds/60;

        seconds = seconds%60;      

        System.out.printf("The amount of [ 290 ] seconds are %02d:%02d:%02d\n",hour,minute,seconds);

         seconds = 7650;
         hour = seconds/60/60;
         minute  = seconds/60;

         seconds = seconds%60;

         System.out.printf("The amount of [ 7650 ] seconds are %02d:%02d:%02d\n",hour,minute,seconds);
    }
}

我在7650的输出不一样为什么? :(

我的解决方案是真的吗?

3 个答案:

答案 0 :(得分:6)

正如@Balwinder在他的评论中提到的,你可能会有一个帮助方法接受秒并打印出格式化的显示时间。下面的代码只需几行即可完成。

public static void printHMS(int secs) {
    int seconds = secs % 60;
    int minutes = (secs / 60) % 60;
    int hours   = (secs / 60) / 60;

    System.out.printf("The amount of [ %d ] seconds are %02d:%02d:%02d\n", secs, hours, minutes, seconds);
}

public static void main(String args[]) {
    printHMS(290);
    printHMS(7650);
}

<强>输出:

The amount of [ 290 ] seconds are 00:04:50
The amount of [ 7650 ] seconds are 02:07:30

答案 1 :(得分:2)

这是因为你没有减去分钟的小时数,所以小时数是双重计算的。也就是说,使用minute = seconds / 60 - hour * 60;代替minute = seconds / 60;,您将获得正确的结果。

实际上,对于第一部分(The amount of [ 290 ] seconds are 00:04:50),您还应该修改代码。它看起来不错的原因是因为290秒不到一个小时,所以问题没有出现。

以下是完整代码:

public class DisplayTime {

    public static void main(String[] args) {

        int seconds = 290;
        int hour = seconds / 60 / 60;
        int minute = seconds / 60 - hour * 60;;

        seconds = seconds % 60;

        System.out.printf("The amount of [ 290 ] seconds are %02d:%02d:%02d\n", hour, minute, seconds);

        seconds = 7650;
        hour = seconds / 60 / 60;
        minute = seconds / 60 - hour * 60;

        seconds = seconds % 60;

        System.out.printf("The amount of [ 7650 ] seconds are %02d:%02d:%02d\n", hour, minute, seconds);
    }
}

结果如下:

The amount of [ 290 ] seconds are 00:04:50
The amount of [ 7650 ] seconds are 02:07:30

答案 2 :(得分:0)

它像专业人士一样:

    /*** Returns the Time**/
public static String getTimeEdited(int seconds) {

    if (seconds / 60 > 60) // Is more than one hour>60
        return String.format("%02d:%02d:%02d",(seconds/60)/60,(seconds/60)%60,seconds%60);
    else                  // Is less than one hour<60
        return String.format("%02d:%02d",(seconds/60)%60,seconds%60);


}