-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calculator
55 lines (42 loc) · 1.57 KB
/
Calculator
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
//A simple calculator built to deal wih user-input errors.
import java.util.Scanner;
import java.util.regex.Pattern;
public class Exercise1 {
public static void main(String[] args) {
String newLine = "";
Pattern p = Pattern.compile(".*[A-Za-z].*");
while (!newLine.equals("0")) {
Scanner s = new Scanner(System.in);
System.out.println("Input desired calculation:");
newLine = s.nextLine();
String first = "";
String second = "";
double ans = 0;
while (p.matcher(newLine).matches()) {
System.out.println("Invalid command!");
newLine = s.nextLine();
}
if (newLine.equals("0")) {
break;
}
if (newLine.contains("*")) {
first = newLine.substring(0, newLine.indexOf("*"));
second = newLine.substring(newLine.indexOf("*")+1, newLine.length());
ans = Double.parseDouble(first) * Double.parseDouble(second);
} else if (newLine.contains("+")) {
first = newLine.substring(0, newLine.indexOf("+"));
second = newLine.substring(newLine.indexOf("+")+1, newLine.length());
ans = Double.parseDouble(first) + Double.parseDouble(second);
} else if (newLine.contains("-")) {
first = newLine.substring(0, newLine.indexOf("-"));
second = newLine.substring(newLine.indexOf("-")+1, newLine.length());
ans = Double.parseDouble(first) - Double.parseDouble(second);
} else if (newLine.contains("/")) {
first = newLine.substring(0, newLine.indexOf("/"));
second = newLine.substring(newLine.indexOf("/")+1, newLine.length());
ans = Double.parseDouble(first) / Double.parseDouble(second);
}
System.out.println(ans);
}
}
}