Java Reference
In-Depth Information
Add
Subtract
Multiply
Divide
F
IGURE
9.14
The program takes an expression in one argument (
operand1 operator
operand2
) from the command line and displays the expression and the result of the
arithmetic operation.
The program is shown in Listing 9.5.
L
ISTING
9.5
Calculator.java
1
public class
Calculator {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Check number of strings passed
5
if
( !=
1
) {
6 System.out.println(
7
"Usage: java Calculator \"operand1 operator operand2\""
);
8 System.exit(
1
);
9 }
10
11
args.length
check argument
// The result of the operation
12
int
result =
0
;
13
14
// The result of the operation
15 String[] tokens = args[
0
].split(
" "
);
16
17
split string
// Determine the operator
check operator
18
switch
(
tokens[
1
].charAt(
0
)
) {
19
case
'+'
: result = Integer.parseInt(
tokens[
0
]
) +
20 Integer.parseInt(
tokens[
2
]
);
21
break
;
22
case
'-'
: result = Integer.parseInt(
tokens[
0
]
) -
23 Integer.parseInt(
tokens[
2
]
);
24
break
;
25
case
'*'
: result = Integer.parseInt(
tokens[
0
]
) *
26 Integer.parseInt(
tokens[
2
]
);
27
break
;
28
case
'/'
: result = Integer.parseInt(
tokens[
0
]
) /
29 Integer.parseInt(
tokens[
2
]
);
30 }
31
32
// Display result
33 System.out.println(
tokens[
0
]
+
' '
+
tokens[
1
]
+
' '
34 +
tokens[
2
]
+
" = "
+ result);
35 }
36 }