-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandLineCalculator.java
More file actions
32 lines (28 loc) · 916 Bytes
/
CommandLineCalculator.java
File metadata and controls
32 lines (28 loc) · 916 Bytes
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
class CommandLineCalculator {
public static void main(String[] args) {
int characters = args.length;
if (characters < 3) {
System.out.println("You did not type in a calculation!");
} else if (characters % 2 == 0) {
System.out.println("Invalid number of command line parameters.");
} else {
Calculator counter = new Calculator();
counter.count(args);
}
}
}
class Calculator {
int count(String[] args) {
int result = Integer.parseInt(args[0]);
for (int i = 1; i < args.length - 1; i += 2) {
String operator = args[i];
int operand = Integer.parseInt(args[i + 1]);
if (operator.equals("+")) {
result += operand;
} else if (operator.equals("-")) {
result -= operand;
}
}
return result;
}
}