import javax.swing.*; /** * This is a simple class that can be used to ask a user to enter * data for a program. * * To use this program, create an instance of this class and * call one of the methods getDouble(), getInt() or getString(). * Each of these methods takes a string parameter, which is displayed * to the user and returns either a double, an int, or a string. */ public class InputDialog { JFrame f; //early forms of BlueJ do not display the dialog //box without a JFrame being created. /** * This is the contructor. It creates a JFrame and makes the * frame visible. The early versions of BlueJ did not show * the dialog box without a frame being created. */ public InputDialog( ) { f = new JFrame(); f.setVisible( true ); } /** * This method gets a double from the user. * * @param message The prompt that is displayed to the user. * @return Either the value entered by the user or, if there is an * error, a 0.0 is returned */ public double getDouble ( String message ) { double answer = 0.0; String tmp = "0"; tmp = JOptionPane.showInputDialog( f, message ); try { answer = Double.parseDouble( tmp ); } catch( NumberFormatException e ) { answer = 0.0; } catch( NullPointerException e ) {answer = 0.0; } return answer; } /** * This method gets an int from the user. * * @param message The prompt that is displayed to the user. * @return Either the value entered by the user or, if there is an * error, a 0 is returned */ public int getInt ( String message) { int answer = 0; String tmp = "0"; tmp = JOptionPane.showInputDialog( f, message ); try { answer = Integer.parseInt( tmp ); } catch( NumberFormatException e ) { answer = 0; } catch( NullPointerException e ) {answer = 0; } return answer; } /** * This method gets a string from the user. * * @param message The prompt that is displayed to the user. * @return Either the value entered by the user or, if there is an * error, an empty string is returned */ public String getString ( String message ) { String answer = ""; answer = JOptionPane.showInputDialog( f, message ); return answer; } }