Java Reference
In-Depth Information
private String numStr1 = "";
private String numStr2 = "";
private char op;
private boolean firstInput = true ;
When an event is generated by a button, the method actionPerformed is executed.
So when the user clicks the = button, the program must display the result. Similarly,
when the user clicks an operation button, the program should prepare to receive the
second number, and so on. We, therefore, see that the instructions to receive the
inputs and operations and display the results will be placed in the method
actionPerformed . Next, we describe this method.
Method
action
Performed
As described above, the method actionPerformed is executed when the user
presses any button. Several things can go wrong while using the calculator. For
example, the user might press an operation button without specifying the first
number, or the user might press the equal button either without specifying a number
or after inputting the first number. Of course, we must also address division by zero.
Therefore, the method actionPerformed must appropriately respond to the errors.
Suppose that the user wants to add three numbers. After adding the first two numbers,
the third number can be added to the sum of the first two numbers. In this case, when
the third number is added, the first number is the sum of the first two numbers and the
second number becomes the third number. Therefore, after each operation, we will set
the first number as the result of the operation. The user can click the C button to start a
different calculation. This discussion translates into the following algorithm:
1. Declare the appropriate variables.
2. Use the method getActionCommand to identify the button clicked.
Retrieve the label of the button, which is a string.
3. Retrieve the character specifying the button label and store it in the
variable ch .
4. a. If ch is a digit and firstInput is true , append the character at
the end of the first number string; otherwise, append the char-
acter at the end of the second number string.
b. If ch is an operation, set firstInput to false and set the
variable op to ch .
c. If ch is = and there is no error, perform the operation, display
the result, and set the first number as the result of the operation.
If an error occurred, display an appropriate message.
d. If ch is C , set both number strings to blank and clear the
displayText .
To perform the operation, we write the method evaluate , which is described in the
next section.
1
1
Search WWH ::




Custom Search