This is a simple Java program designed to calculate the area of a circle based on the radius provided by the user.
It makes use of the mathematical formula for calculating the area of a circle, which is π (pi) times the square of the radius (π * r^2), where π is approximately 3.14.
In this program:
- It imports the java.util.Scanner class to read input from the user.
- It declares two variables, area and radius, to store the calculated area and the radius of the circle, respectively.
- It creates a Scanner object named scanner to read user input.
- It prompts the user to enter the radius of the circle by displaying the message "Enter Radius: " and reads the user's input as a floating-point number.
- It closes the Scanner object to release resources once the input is obtained.
- It calculates the area of the circle using the formula area = 3.14f * radius * radius. Note that it uses an approximation of π (pi) as 3.14.
- It uses System.out.printf to display the calculated area with formatting. %6.2f in the printf format string specifies that the floating-point number (area) should be displayed with a total width of 6 characters and 2 decimal places.
import java.util.Scanner;
public class CircleArea {
public static void main(String[] args) {
float area, radius;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Radius: ");
radius = scanner.nextFloat();
scanner.close();
area = 3.14f * radius * radius;
System.out.printf("Area: %6.2f", area);
}
}
Follow Us