package geometrypack;
public class Calc {
public static double areaOfCircle(int radius) {
if (radius <= 0) {
System.out.println("Input cannot be a negative number.");
}
return (Math.PI * (radius * radius));
} // areaOfCircle method
public static double areaOfRectangle(int length,int width) {
if (length <= 0 || width <= 0) {
System.out.println("Input cannot be a negative number.");
}
return length * width;
} // areaOfRectangle method
public static double areaOfTriangle(int base, int height) {
if (base <= 0 || height <= 0) {
System.out.println("Input cannot be a negative number.");
}
return (base * height) * 0.5;
}
}
所以,我要做的就是讓每個方法在列印錯誤訊息時不回傳該區域。我希望它回傳該區域或回傳錯誤訊息。我嘗試將 return 陳述句放在 else 陳述句中,但該方法不允許這樣做。有什么建議?
uj5u.com熱心網友回復:
你應該拋出一個例外。例如,
if (radius <= 0) {
throw new IllegalArgumentException("Input cannot be a negative number.");
}
uj5u.com熱心網友回復:
或者if在System.out.println.之后的子句中放置一個 return 陳述句。
就像是:
if (radius <= 0) {
System.out.println("Input cannot be a negative number.");
return -1.0;
}
然后你可以檢查 -1.0 的回傳值作為錯誤結果。
讓我們回到 C 編程時代,在出現例外之類的事情之前。:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/346366.html
上一篇:減少if陳述句的更好方法
