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?
CodePudding user response:
You should throw an exception. For example,
if (radius <= 0) {
throw new IllegalArgumentException("Input cannot be a negative number.");
}
CodePudding user response:
Or put a return statement in the if
clause after System.out.println
.
Something like:
if (radius <= 0) {
System.out.println("Input cannot be a negative number.");
return -1.0;
}
Then you can check the return value of -1.0 as an error result.
Brings us back to the C programming days before there were such things as Exceptions. :)