除了return secondarypass
之外,正确的返回语句是什么?
为什么可以返回 Secondpass
并且仍然能够在 IDE IntelliJ 中不出现任何错误并能够运行?
public static void main(String[] args) {
getDurationString(5,2);
}
public static int getDurationString(int minutes, int seconds) {
if (minutes < 0 || seconds < 0 && seconds > 59) {
System.out.println("Invalid value");
}
int hourtomin = (60/minutes);
int secondspass = (seconds/seconds);
System.out.println(hourtomin + "hours" + secondspass + "seconds");
return secondspass;
}
最佳答案
最合乎逻辑的返回结果是来自名为 getDurationString 的方法的持续时间字符串。所以我会将返回类型更改为 String (正如 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
}
}
关于java - 除了 return secondarypass 之外,正确的返回语句是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59675547/