Java Reference
In-Depth Information
Searching for Subsequent Operator Clicks
Figure 6-32 displays the code that executes on subsequent operator clicks.
Beginning with the else statement that executes if the variable first is false (line
210), the code continues with a switch structure to determine which of the oper-
ators was clicked, using the variable lastOp (line 212). The program tests that
variable in line 212 to determine which calculation to perform. The four possible
cases each use an assignment operator to accumulate the result and assign it to
op1, as shown in lines 215, 218, 221, and 224. Recall that the valueOf() method
converts text from the lcd TextField to doubles in order to perform the
operation; each assignment statement, thus, uses a double data type with a
parseDouble() method.
210
else // second operand
211
{
212
switch ( lastOp )
213
{
214
case 10: // divide button
215
op1 /= Double .parseDouble ( lcd.getText ()) ;
216
break ;
217
case 11: // multiply button
218
op1 *= Double .parseDouble ( lcd.getText ()) ;
219
break ;
220
case 12: // minus button
221
op1 -= Double .parseDouble ( lcd.getText ()) ;
222
break ;
223
case 13: // plus button
224
op1 += Double .parseDouble ( lcd.getText ()) ;
225
break ;
226
} // end of switch(lastOp)
227
lcd.setText ( calcPattern.format ( op1 )) ;
228
clearText = true ;
229
FIGURE 6-32
Finally, in line 227, the result is formatted and then assigned to the lcd
TextField. Line 228 sets the flag, clearText, to true so that subsequent numeric
button clicks will begin a new calculation.
The following step enters the code that executes when a user clicks a
subsequent operator button — after clicking the first operator button — in any
calculation.
To Enter Code for Subsequent Operator Button Clicks
1. Enter lines 210 through 229 as shown in Figure 6-32.
The TextPad window displays the code to handle subsequent operator but-
ton clicks in a calculation (Figure 6-33). When executed, the else statement
and switch structure will look for subsequent operator button clicks.
Search WWH ::




Custom Search