Java Reference
In-Depth Information
When called, the getSales() method will execute the code inside its braces.
Line 31 in Figure 4-8 on the previous page uses the showInputDialog() method
of the JOptionPane class to instruct the program to display an input dialog box
with a message and a text box for user input. The showInputDialog() method
has two arguments. The first argument indicates the placement of the dialog box
on the screen. The Java keyword, null, instructs the program to display the dialog
box centered within the program's active window. The second argument, which
is enclosed in quotation marks in line 31, includes the prompt or message to dis-
play inside the dialog box. Unless otherwise specified, the showInputDialog()
method displays a dialog box with a text box, an OK button, and a Cancel
button.
The getSales() method for the Commission program thus causes an input
dialog box to display with a message that prompts the user to enter a sales
amount. After the user enters the value in the text box and clicks the OK button,
line 31 returns and assigns the value to a String variable named answer. In order
for math to be performed on the answer, the parseDouble() method in line 33
converts the value to a double data type and assigns it to a variable location
named sales.
To return the value to the main() method, the last line inside the getSales()
method (line 35) must be a return statement. The return statement indicates
to the JVM that the method is finished and that execution may return to the
main() method. In this program, line 35 returns the value stored in the variable
location, sales, back to the main() method. In the main() method, the returned
value is assigned to a variable location named dollars. The return value and its
resulting storage location, if any, must be of the same data type, but may have
different names. For example, the getSales() method declares and uses the vari-
able location, sales, to store the return value, while the main() method declares
and uses the variable location, dollars, to store the same return value. When a
method is complete, execution always passes back to the next sequential line that
follows the call.
This code does not yet validate or test the value entered by the user in any
way other than when Java tries to convert it to a double, but it does serve as a
stub to allow you to check the method call in line 22.
The following steps enter the code to call the getSales() method and the stub
for the getSales() method.
To Enter Code for the getSales() Method
1. Enter lines 20 through 22 as shown in Figure 4-8 on the previous page.
The main() method will call the getSales() method during execution
(Figure 4-9). Line 20 is a blank line. As you enter new code, the closing
braces for the main() method and class automatically will move down.
Search WWH ::




Custom Search