SHOW:
|
|
- or go back to the newest paste.
1 | public static int calculate(String input){ | |
2 | int lhs,rhs; //short for left-hand & right-hand side | |
3 | char operation; | |
4 | Scanner scanner = new Scanner(input); | |
5 | lhs = scanner.nextInt(); | |
6 | while(scanner.hasNext()) { | |
7 | operation = scanner.next().charAt(0); | |
8 | rhs = scanner.nextInt(); | |
9 | - | lhs = lhs + operation + rhs; |
9 | + | switch(operation) { |
10 | case '+': | |
11 | lhs += rhs; | |
12 | break; | |
13 | case '-': | |
14 | lhs -= rhs; | |
15 | break; | |
16 | case '*': | |
17 | lhs *= rhs; | |
18 | break; | |
19 | case '/': | |
20 | lhs /= rhs; | |
21 | break; | |
22 | default: | |
23 | //error!! wrong operation, do something | |
24 | break; | |
25 | } | |
26 | System.out.println(lhs); | |
27 | ||
28 | } | |
29 | ||
30 | ||
31 | ||
32 | ||
33 | ||
34 | /*todo: your name and code goes here*/ | |
35 | /*You need a Scanner(or StringTokenizer) to get tokens | |
36 | *Then you need a loop, and switch inside that loop*/ | |
37 | return lhs; | |
38 | } |