The program below is the answer to Liang’s Introduction to Java Programming (9th Edition) Chapter 2 Exercise 2.2.

1 2 |
/**<br /> *<br /> * @Author: Aghatise Osazuwa<br /> * Website: www.cscprogrammingtutorials.com<br /> *<br /> * Exercise 2.2 - Compute The Volume Of A Cylinder<br /> *<br /> */ <br /><br />import java.util.Scanner;<br /><br />public class VolumeOfCylinder {<br /> public static void main (String [] args) {<br /> Scanner input = new Scanner(System.in);<br /> System.out.println("This Program Computes The Area And Volume Of A Cylinder.n");<br /> System.out.println("Enter the radius and length of a cylinder separated "<br /> + "by a space or by pressing the ENTER key: ");<br /> double radius = input.nextDouble();<br /> double length = input.nextDouble();<br /> double area = radius * radius * Math.PI;<br /> double volume = area * length;<br /> <br /> System.out.printf ("%s%.2f%s%.2f%s", "The Area is ", area, <br /> "nThe Volume is ", volume, "n");<br /> }<br />}<br /> |

Click here to see other solutions to Introduction to Java Programming.

## 2 Comments

The question did not specify how many decimal places the answer should be. But if you want yours to be like the sample run used in the textbook, you only need to change the format of the System.out.printf statement like this

System.out.printf ("%s%.4f%s%.1f%s", "The Area is ", area, "nThe Volume is ", volume, "n");part of this exercise is to use type casting to truncate the area's decimal places so the answer won't be as long. The area is shown with only 4 decimal numbers and the volume shows only one. Would you happen to know how to add that to the computation?