我是Java的真正初学者,我做了一个简单的练习,需要使用一种方法将m / h转换为km / h并从中返回。
我必须定义两种情况:如果km / h 0返回km / h * 1.609(以m / h表示的值)。
我尝试了所有可能想到的方法,但是尝试运行它时,我得到了no return statement错误或没有输出。
我不明白为什么即使我给了它多个返回选项,但不管它的值是什么,它都不起作用。我可以使用System.outprintln或String,但是练习指定我必须使用return方法。
这是我用IntelliJ编写的代码:
package EXERCISE;
public class Main {
public static void main(String[] args) {
toMilesPerHour(0);
}
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else if (kilometersPerHour > 0) {
return kilometersPerHour * 1.609d;
}
else if (kilometersPerHour == 0) {
return 0;
}
return kilometersPerHour * 1.609;
// if I don't write return here it gives me no return statement error,
// if I write it, it gives me no output with value > or < 0 but no error.
}
}
最佳答案
即使使用方法,也必须打印返回值:
package EXERCISE;
public class Main {
public static void main(String[] args) {
System.out.println(toMilesPerHour(0));
}
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else if (kilometersPerHour > 0) {
return kilometersPerHour * 1.609d;
}
else if (kilometersPerHour == 0) {
return 0;
}
return kilometersPerHour * 1.609;
//if I don't write return here it gives me no return statement error,
//if I write it, it gives me no output with value > or < 0 but no error.
}
}
此外,您可以在最后摆脱return语句:
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else {
// you don't need to check if kilometersPerHour is 0, since every number multiplied with 0 is 0
return kilometersPerHour * 1.609;
}
}