Search code examples
javaconditional-statementsstatic-methods

if/else statement issues within static methods


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;
    }
}

So, all I'm trying to do is get each method to not return the area when printing the error message. I want it to either return the area or return the error message. I tried putting the return statement within an else statement but the method won't allow that. Any suggestions?


Solution

  • You should throw an exception. For example,

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