-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathCalculator.java
More file actions
39 lines (36 loc) · 1.18 KB
/
Calculator.java
File metadata and controls
39 lines (36 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.serenitydojo.calculator;
import java.util.ArrayList;
import java.util.List;
public class Calculator {
public int evaluate(String expression)
{
if(!expression.isEmpty()) {
String[] inputString = expression.split(" ");
int i = 1;
int total = Integer.parseInt(inputString[0]);
while (i < inputString.length) {
switch (inputString[i]) {
case "+":
total = total + Integer.parseInt(inputString[i + 1]);
i = i + 2;
break;
case "-":
total = total - Integer.parseInt(inputString[i + 1]);
i = i + 2;
break;
case "*":
total = total * Integer.parseInt(inputString[i + 1]);
i = i + 2;
break;
default:
throw new IllegalMathsOperatorException("Operator Not Found "+inputString[i]);
}
}
return total;
}
else
{
return 0;
}
}
}