返回的最合乎逻辑的东西是来自名为 getDurationString 的方法的持续时间字符串。所以我会将返回类型更改为字符串(正如 MadProgrammer 所暗示的那样)。此外,由于该方法没有表明它将打印某些内容,因此样式会说让调用者处理输出。最后,为了回答另一个问题,IDE 很乐意让您从返回类型为 int 的方法返回一个 int (secondspass),即使它不是您想要的或计算不正确。
我调整了计算和检查以首先将秒转换为分钟(以防秒导致分钟超过一个小时 - 我这样做是因为我想让秒 > 59),然后打破分钟减少到小时和秒(加上原来的秒)。代码如下(我还尝试了驼峰式变量;也请注意,由于传递的变量是原始类型,我可以安全地修改它们而不会对调用者产生副作用)。
public class TimeString {
public static String getDurationString(int minutes, int seconds) {
//since this method is called get, having a side-effect like printing something is undesirable
if (minutes < 0 || seconds < 0) { //enhanced to handle seconds > 59
return "Invalid value";
}
//handle any seconds that could be minutes
minutes += seconds / 60;
seconds %= 60;
int hours = (minutes / 60);
minutes %= 60;
seconds = (seconds + 60 * minutes);
return hours + " hours " + seconds + " seconds"; //note spaces so things look nice, you asked for hours and seconds, hours, minutes, and seconds is more usual
}
public static void main(String args[]) {
System.out.println(getDurationString(105, 900));
}
}
其他想法:
在一段时间内使用小时、秒和无分钟似乎非常不合常规。如果将分钟保留为分钟而不是将其转换为秒,则代码如下所示。
public class TimeString {
public static String getDurationString(int minutes, int seconds) {
//since this method is called get, having a side-effect like printing something is undesirable
if (minutes < 0 || seconds < 0) { //enhanced to handle seconds > 59
return "Invalid value";
}
//handle any seconds that could be minutes
minutes += seconds / 60;
seconds %= 60; //and mod by 60 to get any remaining seconds
int hours = (minutes / 60);//handle whether there are full hours from the minutes
minutes %= 60;// and mod by 60 to get the remaining minutes
//removed line converting minutes back to seconds
return hours + " hours " + minutes + " minutes " + seconds + " seconds"; //note spaces so things look nice, you asked for hours and seconds, hours, minutes, and seconds is more usual
}
public static void main(String args[]) {
System.out.println(getDurationString(95, 79));// should become 1 hours 36 minutes 19 seconds
}
}