Find that Cylinder's Volume! (part II)

| Posted in , , | Posted on 11:41 PM


Computers may be incredibly efficient but they are also equally dumb.

  1. Ask user for radius.
  2. Ask user for cylinder length.
  3. Tell user cylinder volume.
Sounds simple enough... until the program breaks down because the the user gives the computer a bunk number for either the length or radius. Plug in a negative radius and the program will compute a negative volume. Last I checked negative volumes aren't possible, but I could be wrong. Next time I check in with Steven Hawking I'll ask him about negative volumes.

Assuming we want positive volumes then we'd also want positive lengths and radii. Here's a modified version of "Find that Cylinder's Volume" that uses if/else to test the input. If it finds a negative value it prints the error and exits.


/*
 * This is a basic application meant to calculate
 * the area of a circle. It's an improvement on past
 * program because it verifies input as a positive number.
 */

package calculateareaofcircle2;
import javax.swing.JOptionPane;

/**
 * @author Neil
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

    // Prompt user for radius of cylinder and store it as variable
    String stringRadius = JOptionPane.showInputDialog(null, "Enter the"
           + " radius of the cylinder.", "Find that Volume!",
           JOptionPane.QUESTION_MESSAGE);
    // Convert string value to a double variable
    double radius = Double.parseDouble(stringRadius);

if (radius >= 0) {

    // Prompt user for the length of the cylinder and
    // store it as a variable
    String stringLength = JOptionPane.showInputDialog(null, "Enter the"
            + " length of the cylinder.", "Find that Volume!",
            JOptionPane.QUESTION_MESSAGE);
    // Convert string value to a double variable
    double length = Double.parseDouble(stringLength);

    if (length >=0) {

    /*
     * Calculate the volume of the cylinder by first finding the area
     * of the  base and then multiplying it by the length.
     */

    // Declare area, calculate it, and  then store it
    double area = (radius * radius) * 3.141593;

    // Declare volume, calculate it, and then store it
    double volume = area * length;

    // Display result of calculation
    JOptionPane.showMessageDialog(null, "A cylinder that is " + length +
    " long and " + radius + " in radius has a volume of " + volume,
    "Find that Volume!", JOptionPane.QUESTION_MESSAGE);
        }
else {
    JOptionPane.showMessageDialog(null, "The cylinder length must be "
    + "a positive number.");
 }
        }
else {
    JOptionPane.showMessageDialog(null, "The radius must be a positive "
                + "number.");
        }
    }
}

Comments Posted (0)

Post a Comment