1. Introduction
Calculating the area of a circle is a common programming task that allows beginners to practice using mathematical operations, constants, and user input in Java. The formula to calculate the area of a circle is Area = π * r², where π represents the mathematical constant pi, and r represents the radius of the circle.
2. Program Steps
1. Import the Scanner class from the java.util package for user input.
2. Define the main class named AreaOfCircle.
3. Inside the main class, define the main method.
4. Inside the main method, create an object of the Scanner class to take user input.
5. Prompt the user to enter the radius of the circle and store it in a variable.
6. Calculate the area of the circle using the formula Area = π * r².
7. Print the calculated area to the console.
3. Code Program
import java.util.Scanner; // 1. Importing Scanner class for user input
public class AreaOfCircle { // 2. Defining the main class
public static void main(String[] args) { // 3. Defining the main method
Scanner input = new Scanner(System.in); // 4. Creating Scanner object to take user input
System.out.print("Enter the radius of the circle: "); // 5. Prompting user for the radius
double radius = input.nextDouble(); // Storing the radius in variable radius
double area = Math.PI * Math.pow(radius, 2); // 6. Calculating the area using the formula Area = π * r²
System.out.println("The area of the circle with radius " + radius + " is: " + area); // 7. Printing the calculated area
input.close(); // Closing the Scanner object to avoid memory leak
}
}
Output:
Enter the radius of the circle: 5 The area of the circle with radius 5.0 is: 78.53981633974483
4. Step By Step Explanation
– Step 1: The Scanner class from the java.util package is imported to take user input.
– Step 2: The main class AreaOfCircle is defined.
– Step 3: The main method, which serves as the entry point of the Java program, is defined inside the main class.
– Step 4: An object of the Scanner class named "input" is created for reading user input.
– Step 5: The user is prompted to enter the radius of the circle, 5, which is then stored in the variable radius.
– Step 6: The area of the circle is calculated using the formula Area = π * r², where π is represented by Math.PI and r is the value stored in the variable radius. The result, 78.53981633974483, is stored in the variable area.
– Step 7: Finally, the calculated area of the circle is printed to the console.
– The Scanner object is then closed to prevent resource leak.