In: Computer Science
Write a method named area with one double parameter name radius. The method needs to return a double value that represents the area of a circle. If the parameter radius is negative , then return -1.0 to present an invalid value
Write another overload method with 2 parameters side1 and side2 (both double) where side1 and side2 represent the sides of a rectangle. The method needs to return an area of a rectangle . If either or both parameters is/ are negative return -1.0 indicate an invalid value.
Example output:
area(5.0) should return 78.53975
area(-1) should return -1 since the parameter is nagative
area(5.0, 6.0) should return 30.0 (5 * 6 = 30)
All method need to be defined as public static
Add a main method to your solution code
Please write in Java
Explanation:
Here is the code which has 2 methods, both having the same name area() but different number of parameters.
Code:
public class Main
{
public static double area(double radius)
{
if(radius<0)
return -1.0;
return Math.PI*radius*radius;
}
public static double area(double side1, double side2)
{
if(side1<0 || side2<0)
return -1.0;
return side1*side2;
}
public static void main(String[] args) {
System.out.println(area(5.0));
System.out.println(area(-1.0));
System.out.println(area(5.0,
6.0));
}
}
Output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!