2.12. Case Studies

 
[Page 45 ( continued )]

2.11. Getting Input from Input Dialogs

In Listing 2.1, the radius is fixed in the source code. To use a different radius, you have to modify the source code and recompile it. Obviously, this is not convenient . You can use the showInputDialog method in the JOptionPane class to get input at runtime. When this method is executed, a dialog is displayed to enable you to enter an input value, as shown in Figure 2.2.

Figure 2.2. The input dialog box enables the user to enter a string.

After entering a string, click OK to accept the input and dismiss the dialog box. The input is returned from the method as a string. You can invoke the method with four arguments, as follows :

The first argument can always be null . The second argument is a string that prompts the user. The third argument is the title of the input box. The fourth argument can be JOptionPane.QUESTION_MESSAGE , which causes the icon ( ) to be displayed in the input box.

Note

There are several ways to use the showInputDialog method. For the time being, you only need to know two ways to invoke it.



[Page 46]

One is to use a statement as shown in the example:

  String string = JOptionPane.showInputDialog(   null   , x,   y, JOptionPane.QUESTION_MESSAGE));  

where x is a string for the prompting message, and y is a string for the title of the input dialog box.

The other is to use a statement like this one:

  JOptionPane.showInputDialog(x);  

where x is a string for the prompting message.

2.11.1. Converting Strings to Numbers

The input returned from the input dialog box is a string. If you enter a numeric value such as 123 , it returns "123" . You have to convert a string into a number to obtain the input as a number.

To convert a string into an int value, use the parseInt method in the Integer class, as follows:

    int   intValue = Integer.parseInt(intString);  

where intString is a numeric string such as "123" .

To convert a string into a double value, use the parseDouble method in the Double class, as follows:

    double   doubleValue = Double.parseDouble(doubleString);  

where doubleString is a numeric string such as "123.45" .

The Integer and Double classes are both included in the java.lang package, and thus are automatically imported.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net