Write a program to calculate the area of a circle by entering the radius. Formula: area=PI*r*r.
Logic:
To calculate the area of a circle we use formula area= 22/7 * r*r. For this, we input the radius value and PI value from Math.PI.
/*
Calculate Circle Area using Java Example
This Calculate Circle
Area using Java Example shows how to calculate
area of a circle using
its radius.
This program will help for ICSE, ISC and BCA students
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CalculateCircleAreaExample
{
public static
void main(String[] args)
{
int radius = 0;
//Local
variable
System.out.println("Please enter radius of a circle");
try
{
//get the radius from a console
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
radius = Integer.parseInt(br.readLine());
}
//if an invalid value was entered
catch(NumberFormatException ne)
{
System.out.println("Invalid
radius value" + ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println("IO Error :" + ioe);
System.exit(0);
}
/*
* Area of a circle is
* Formula area=pi * r * r
* where r is a radius of a circle.
*/
// NOTE: use
Math.PI constant to get the value of Pi
double area = Math.PI * radius * radius;
// Print the value of the area of a circle
System.out.println("Area of a circle is " + area);
}
}
Output:
Please enter radius of a circle
12
Area of a circle is 452.3893421169302
Sl. No.
|
Variable Name
|
Data Type
|
Purpose
|
1
|
radius
|
double
|
Store the radius value
|
2
|
area
|
double
|
Store the area of a circle
|
3
|
main()
|
static void
|
Main function
|
4
|
in
|
InputStreamReader
|
To instantiate the InputStreamReader class which exists in
java.io package
|
5
|
br
|
BufferedReader
|
To instantiate the BufferedReader class which exists in java.io
package using the above variable as the passing parameter
|