Duy*_*rần 3 java methods overloading return
我是Java的新手,我自己也在学习.我尝试重载方法时遇到了麻烦.这是代码
public static void main(String[] args) {
calculateScore();
calculateScore(500);
calculateScore("Duy", 600);
calcFeetAndInchesToCentimetres(100, 3.5);
calcFeetAndInchesToCentimetres(100*12 + 3.5);
}
public static double calcFeetAndInchesToCentimetres(double feet, double inches) {
if (feet >= 0 && inches >= 0 && inches <= 12) {
double footToInches = feet * 12;
double centimetres = (inches + footToInches) * 2.54;
System.out.println("The value in centimetres is " + centimetres + " cm.");
return centimetres;
} else {
return -1;
}
}
public static double calcFeetAndInchesToCentimetres(double inches) {
if (inches >= 0){
double inchesToFeet = inches / 12;
double inchesRemain = inches - (inchesToFeet * 12);
calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
return 0;
} else {
return -1;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是当我return 0从第二种方法中取出时,调试器会说"缺少return语句".然后我试着放return calcFeetAndInchesToCentimetres(inches);,它有效,但程序运行了大约数千次.
然后我把return 0,一切都好.但是我不明白为什么我不能把它return calcFeetAndInchesToCentimetres(inches);和为什么我需要一个return语句,当上面的方法(有2个参数)有它时.如果我想在执行第二种方法时转换厘米的值(仅使用"inches"参数),我该怎么做?
我在块代码中意识到的另一件事
double inchesToFeet = inches / 12;
double inchesRemain = inches - (inchesToFeet * 12);
calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
Run Code Online (Sandbox Code Playgroud)
inchesRemain将为0?但该方法效果很好.当我改变时inchesToFeet = inches % 12,它只是没有显示任何东西.为什么?
它应该只是:
public static double calcFeetAndInchesToCentimetres(double inches) {
if (inches >= 0){
double inchesToFeet = inches / 12;
double inchesRemain = inches - (inchesToFeet * 12);
return calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
} else {
return -1;
}
}
Run Code Online (Sandbox Code Playgroud)
你说你已经尝试了return calcFeetAndInchesToCentimetres(inches);但是这只是递归地调用你的方法而且它会永远地递归,因为没有停止条件.
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |