The problem
In this example write a program that reads in the radius and length of a cylinder and computes the area and volume.
area = radius * radius * p
volume = area * length
Here is a sample run:
Enter the radius and length of a cylinder: 5.5 12
The area is 95.0331
The volume is 1140.4
Breaking it down
Sticking to the basics and reading two numbers from the user that represent the radius and length of a cylinder we will pass those values to calculateArea
and calculateVolume
. Finally we will output the calculations back to the console. Remember, in its current state the program doesn't validate the users input which could lead to errors.
public static void main(String[] Strings) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the radius and the length of a cylinder: ");
double radius = input.nextDouble();
double length = input.nextDouble();
input.close();
double area = calculateArea(radius);
double volume = calculateVolume(length, area);
System.out.println("The area is " + area);
System.out.println("The volume is " + volume);
}
private static double calculateVolume(double length, double area) {
double volume = area * length;
return volume;
}
private static double calculateArea(double radius) {
double area = radius * radius * 3.14159265359;
return area;
}
Output
Enter the radius and the length of a cylinder: 10 10
The area is 314.159265359
The volume is 3141.5926535900003