静态方法中的 if/else 语句问题

For*_*ure 1 java static-methods conditional-statements

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,我想做的就是让每个方法在打印错误消息时不返回该区域。我希望它返回该区域或返回错误消息。我尝试将 return 语句放在 else 语句中,但该方法不允许这样做。有什么建议么?

小智 5

你应该抛出一个异常。例如,

if (radius <= 0) {
    throw new IllegalArgumentException("Input cannot be a negative number.");
}
Run Code Online (Sandbox Code Playgroud)