首页 > 解决方案 > Java 代码(按预期)适用于除一个输入之外的众多输入:500,000

问题描述

我正在尝试制作一个时间计算器。(之前发过一篇文章,我修好了)。代码按预期工作,除非我输入数字 500,000。它只是在没有打印语句的情况下自动终止程序。但是,如果我愿意,我可以输入 1 - 488888 和 544444 - 900000 之间的任何内容,并且它会起作用。

我已经移动了我的 if 语句,在这里和那里嵌套了一些。我无法判断 if/else if 语句中问题出在哪里。


final int x = 9;
final int y = 1;
final int Days;
final int Hours;
final int Minutes;
final int Seconds;

Days = total_seconds / 86400;
Hours = (total_seconds % 86400 ) / 3600;
Minutes = ((total_seconds % 86400 ) % 3600 ) / 60;
Seconds = ((total_seconds % 86400 ) % 3600 ) % 60;

if (Hours == 0) {

    if (Minutes < x || Seconds < x) {
    String padded = String.format("%02d" , Minutes);
    String padded2 = String.format("%02d" , Seconds);

    System.out.print("You entered " + total_seconds + " second(s), which is " + Minutes + " minute(s), and " +  Seconds + " second(s).");
    System.out.print("\n");
    System.out.print(padded + ":" + padded2);
    }
}
else if (Hours >= y && Days == 0) {
    if (Minutes < x || Seconds < x) {
    String padded = String.format("%02d" , Minutes);
    String padded2 = String.format("%02d" , Seconds);

    System.out.print("You entered " + total_seconds + " second(s), which is " + Hours + " hour(s), " + Minutes + " minute(s), and " +  Seconds + " second(s).");
    System.out.print("\n");
    System.out.print(Hours + ":" + padded + ":" + padded2 + " hours.");
    }
}

else if (Days >= y && Hours >= y) {
    if (Minutes < x || Seconds < x) {
    String padded = String.format("%02d" , Minutes);
    String padded2 = String.format("%02d" , Seconds);

    System.out.print("You entered " + total_seconds + " second(s), which is " + 
    Days + " day(s), " + Hours + " hour(s), " + padded + " minute(s), and " + 
    padded2 + " second(s).");
    System.out.print("\n");
    System.out.print(Days + " day(s) " + Hours + ":" + padded + ":" + padded2 + 
    " hour(s).");
    }
}

else {

System.out.print("You entered " + total_seconds + " second(s), which is " + Days + " day(s), " + Hours + " hour(s), " + Minutes + " minute(s), and " + Seconds + " second(s).");
System.out.print("\n");
System.out.print(Days + " day(s) " + Hours + ":" + Minutes + ":" + Seconds + " hour(s).");
}

当我输入任何具有天数的数字时,它应该输出:

“您输入了 500,000 秒,即 5 天 18 小时 53 分 20 秒。(5 天 18:53:20 小时)”

实际输出(当我输入 500,000 时)绝对没有。该程序只是自动终止而不打印。

我已添加else,但问题仍然存在。

标签: java

解决方案


我不知道你的代码有什么问题,但我认为你应该在这里使用模数,而不是String#format

public String printTimes(int input) {
    int seconds = input % 60;
    int minutes = (input / 60) % 60;
    int hours = (input / 3600) % 60;
    int days = input / (3600*24);

    String output = "You entered " + input + " seconds, which is " +
         days + " days, " + hours + " hours, " + minutes + " minutes and " +
         seconds + " seconds (" + days + " days " + hours + ":" + minutes + ":" +
         seconds + " hours)";

    return output;
}

推荐阅读