/** * */ package hornick; import java.text.DecimalFormat; import javax.swing.JOptionPane; /** * @author hornick * 10/16/2007 * Solution to Lab1 volume calculator demonstrated in class, with an additional method added */ public class VolumeCalculatorApp { /** * main() method is the starting point for all Java applications * @param args */ public static void main(String[] args) { // ask the user for input, and convert the input to a numerical value String input; input = JOptionPane.showInputDialog("Enter the radius of a sphere"); double radius; radius = Double.parseDouble(input); if( radius <= 0.0 ) { // check for invalid radius JOptionPane.showMessageDialog(null, "Error. Radius is <= 0" ); } else { // radius is valid double volume; volume = calculateVolume(radius); // call a method to do the actual computation // convert the numerical result to a string with proper formatting DecimalFormat sdf; sdf = new DecimalFormat("00.000"); String output = sdf.format(volume); // format the output JOptionPane.showMessageDialog(null, "Volume of sphere: " + output + "\nPress OK to exit.", "Result", 2); } } /** * This is a "worker" method that does the actual volume calculation * @param r the radius of the sphere * @return the volume of the sphere */ public static double calculateVolume(double r) { double v = 4./3 * Math.PI * r*r*r; // instead of r*r*r, you can use Math.pow(r,3) return v; } }