/** * */ 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; double radius; int answer=0; do { input = JOptionPane.showInputDialog("Enter the radius of a sphere"); if( input==null ) { System.exit(0); } if( input.length()==0 ) { answer = JOptionPane.showConfirmDialog(null, "Want to try again?", "You entered an empty string", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } } while( answer == JOptionPane.YES_OPTION); if( answer != JOptionPane.YES_OPTION ) System.exit(0); radius = Double.parseDouble(input); // assuming that the input was a valid set of characters representing a number if( radius < 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; } }