java - 如何解决这个问题? java作业

标签 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 中的输出不一样,为什么? :(

我的解决方案是真的吗?

最佳答案

正如 @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

关于java - 如何解决这个问题? java作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33818567/

相关文章:

java - 将简单的 JSON 字符串转换为对象

java - 在 gradle 的 eclipse 构建中拆分 main 和 test

java - 在 Java 中为 XML 编码文本数据的最佳方法是什么?

java - 如何让 Eclipse 智能感知自动完成成员名称?

java - 在所有线程的同步块(synchronized block)中初始化静态变量,无需同步即可读取

java - 想要将库导入到我的 Java 项目中

java - 从我的应用程序中注销 Google

java - 将 iPhone 应用程序转换为 Android 应用程序——我需要了解 Objective C 吗?

java - 为intelliJ设置JAVA_HOME?

java - 如何针对 double 和 int 进行转换