I got the below question for an assignment in my Java class.
Write a Java method to find & print the area of a circle when user input the radius.
I came up with 2 solutions,
Solution 1: Call a void method where the method does all the inputs and calculations and prints the output.
import java.util.*;
class Example{
public static void area(){
Scanner input = new Scanner (System.in);
double area = 0;
double radius = input.nextInt();
area = 3.14 * radius * radius;
System.out.println("Area is: " + area);
}
public static void main(String args[]){
System.out.println("Input the radius: ");
area();
}
}
Solution 2: Call a parameterized double method. Here the input is fed to the main method and calculation is done in the double method and value is returned back to the main method.
import java.util.*;
class Example{
public static double area(double r){
double area = 0;
area = 3.14 * r * r;
return area;
}
public static void main(String args[]){
System.out.println("Input the radius: ");
Scanner input = new Scanner (System.in);
double radius = input.nextDouble();
System.out.println("Area is: " + area(radius));
}
}
I am wondering what is the best coding practice. Solution 1 or 2 and why is that? Thanks in advance for all the responses.
>Solution :
The second version is better because it separates the concerns of (a) calculating the area from (b) what to do with the results.
You don’t need to declare double area = 0 before you assign a value to it. You can simply write:
double area = 3.14 * r * r;
But, in fact, you don’t need to declare a variable at all in that method. You can return the value.
public static double area(double r){
return 3.14 * r * r;
}
You can also use the Math constant for PI:
public static double areaOfCircle(double r){
return Math.PI * r * r;
}