forked from irsyahms/clean-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calculator.java
57 lines (49 loc) · 1.87 KB
/
Calculator.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.*;
class Calculator {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Input number and operators that you want to calculate: ");
try {
String nextLine = in.next();
List<String> nuOps= new ArrayList<String>();
//parsing input menjadi ArrayList berdasarkan angka dan operator
String temp = "";
for (int i = 0; i < nextLine.length(); i++) {
if(nextLine.charAt(i) == '+' || nextLine.charAt(i) == '-' || nextLine.charAt(i) == '/') {
nuOps.add(temp);
nuOps.add(String.valueOf(nextLine.charAt(i)));
temp = "";
} else {
temp = temp + String.valueOf(nextLine.charAt(i));
}
if (i == nextLine.length() - 1) {
nuOps.add(temp);
temp = "";
}
}
//perhitungan
double t = 0;
for (int i = 0; i < nuOps.size(); i++) {
switch (nuOps.get(i)) {
case "+":
i++;
t = t + Double.parseDouble(nuOps.get(i));
break;
case "-":
i++;
t = t - Double.parseDouble(nuOps.get(i));
break;
case "/":
i++;
t = t / Double.parseDouble(nuOps.get(i));
break;
default:
t = Double.parseDouble(nuOps.get(i));
}
}
System.out.println("** Result: " + t);
} catch (InputMismatchException e) {
System.out.println("Invalid input");
}
}
}