The user is first prompted to enter a radius. Then the circumference and area of the circle are calculated, rounded and output to the screen.
Line | Description |
---|---|
1 | Includes the Scanner class for standard input and output |
5 | Initializes the variable reader of type Scanner with a new Scanner object with the input Parameter System.in (to read from the standard input) |
6 | Declares the variables r , area and circumference of type double |
8 – 9 | Prompts the user to enter a radius as an double value. The value is stored in the variable named r |
10 | Closes the variable reader of type Scanner to terminate user input and free the memory space again |
13 | Calculates the circumference of the circle with the formula 2 * Math.PI * r . The number PI can be retrieved via the Math class. The result of this calculation is stored in the variable circumference |
17 | Calculates the circular area of the circle with the formula Math.PI * Math.pow(r, 2) . The pow() method calculates the power of a number by raising the first argument to the second argument. The result of this calculation is stored in the variable area |
19 | Outputs the circumference rounded to 2 decimal places |
20 | Outputs the circular area rounded to 2 decimal places |
import java.util.Scanner;
class CircumferenceCircularArea {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double r, area, circumference;
System.out.print("Please enter radius: ");
r = reader.nextDouble();
reader.close();
// calculation of circumference
circumference = 2 * Math.PI * r;
// calculation of circular area
// Math.pow(base, exponent): Returns base raised to the power exponent
area = Math.PI * Math.pow(r, 2);
System.out.println("Circumference: " + String.format("%1.2f", circumference));
System.out.println( "Circular Area: " + String.format("%1.2f", area));
}
}
Please enter radius: 4.5
Circumference: 28.27
Circular Area: 63.62