Java Reference
In-Depth Information
try
try {
result = Double . parseDouble ( aNumber );
System . out . println ( "Number is " + result );
} catch
catch ( NumberFormatException exc ) {
System . out . println ( "Invalid number " + aNumber );
return
return ;
}
}
Discussion
Of course, that lets you validate only numbers in the format that the designers of the wrapper
classes expected. If you need to accept a different definition of numbers, you could use regu-
lar expressions (see Chapter 4 ) to make the determination.
There may also be times when you want to tell if a given number is an integer number or a
floating-point number. One way is to check for the characters ., d , e , or f in the input; if one
of these characters is present, convert the number as a double . Otherwise, convert it as an
int :
public
public class
class GetNumber
GetNumber extends
extends Frame {
/** The input textField */
private
private TextField textField ;
/** The results area */
private
private TextField statusLabel ;
/** Constructor: set up the GUI */
public
public GetNumber () {
Panel p = new
new Panel ();
p . add ( new
new Label ( "Number:" ));
p . add ( textField = new
new TextField ( 10 ));
add ( BorderLayout . NORTH , p );
textField . addActionListener ( new
new ActionListener () {
public
public void
void actionPerformed ( ActionEvent ev ) {
String s = textField . getText ();
statusLabel . setText ( process ( s ). toString ());
}
});
add ( BorderLayout . SOUTH , statusLabel = new
new TextField ( 10 ));
pack ();
}
Search WWH ::




Custom Search