Java Reference
In-Depth Information
23
empCode = getCode () ;
53
54
//The getCode() method retrieves a code from the user and validates it.
55
public static int getCode ()
56
{
57
//declare method variables
58
int code = 0;
59
boolean done = false ;
60
61
//loop while not done
62
while ( !done )
63
{
64
try
65
{
66
String message = "Enter the commission code:" +
"\n\n1) Telephone Sales\n2) In-Store Sales\n3) Outside Sales\n\n" ;
67
68
code = Integer .parseInt ( JOptionPane.showInputDialog ( null ,message ))
69
70
//test for valid codes 1, 2, or 3
71
if ( code<1 || code>3 ) throw new NumberFormatException () ;
72
else done = true ;
73
}
74
catch ( NumberFormatException e )
75
{
76
JOptionPane.showMessageDialog ( null , "Please enter a 1, 2, or 3." ,
"Error" ,JOptionPane.INFORMATION_MESSAGE ) ;
77
}
78
}
79
return code;
80
}
FIGURE 4-24
Line 66 assigns the String data used to define the prompt to a variable
named message. The String data includes the user prompt, Enter the commis-
sion code:, followed by a numbered list of valid commission codes. Recall that
the escape character sequence, \n, will cause the data that follows it to print on a
new line. When you convert this program to an applet later in the chapter, you
will learn how to create option buttons from which the user can choose a com-
mission code. For this application, however, the numbered list presents an easy
to understand set of choices to the user.
In line 68, the variable, message, is included as the second argument of the
showInputDialog() method, which will cause the message to display as a prompt
in the Input dialog box. The value entered by the user serves as the return value
of the method and thus becomes the argument for the parseInt() method. After
the input is returned and parsed, it then is assigned to the variable, code. Wrap-
ping a method inside another, as shown in line 68, commonly is used in Java
programming because it reduces the number of lines of code.
Line 71 uses the logical OR operator to test for commission codes less than
one or greater than three. In either case, a NumberFormatException is explicitly
thrown, and execution transfers to the catch statement, which displays a message
in an Error dialog box (line 76). The program then loops back to allow the user
to reenter a new, valid commission code.
Line 79 returns the valid code to the calling statement in line 23, where it is
assigned to the variable, empCode.
Search WWH ::




Custom Search