File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
OOP in Java/Chapter 10 - Object-Oriented Thinking/Code_Example Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ package ch_10 ;
2+
3+ /**
4+ * 10.26 (Calculator) Revise Listing 7.9, Calculator.java, to accept an expression as
5+ * a string in which the operands and operator are separated by zero or more
6+ * spaces. For example, 3+4 and 3 + 4 are acceptable expressions.
7+ */
8+ public class Exercise10_26 {
9+ public static void main (String [] args ) {
10+
11+ StringBuilder str = new StringBuilder ();
12+
13+ for (String arg : args ) {
14+ str .append (arg );
15+ }
16+
17+ String str2 = str .toString ().replaceAll (" " , "" );
18+
19+ str2 = str2 .replaceAll ("[+]" , "%+%" );
20+ str2 = str2 .replaceAll ("[-]" , "%-%" );
21+ str2 = str2 .replaceAll ("[.]" , "%.%" );
22+ str2 = str2 .replaceAll ("[/]" , "%/%" );
23+
24+
25+ args = str2 .split ("%" );
26+
27+ int result = 0 ;
28+
29+ switch (args [1 ].charAt (0 )) {
30+
31+ case '+' :
32+ result = Integer .parseInt (args [0 ]) + Integer .parseInt (args [2 ]);
33+ break ;
34+
35+ case '-' :
36+ result = Integer .parseInt (args [0 ]) - Integer .parseInt (args [2 ]);
37+ break ;
38+
39+ case '.' :
40+ result = Integer .parseInt (args [0 ]) * Integer .parseInt (args [2 ]);
41+ break ;
42+
43+ case '/' :
44+ result = Integer .parseInt (args [0 ]) / Integer .parseInt (args [2 ]);
45+ break ;
46+
47+ }
48+ System .out .println (args [0 ] + ' ' + args [1 ] + ' ' + args [2 ] + " = " + result );
49+ }
50+
51+ }
You can’t perform that action at this time.
0 commit comments