-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathOperation.java
More file actions
65 lines (54 loc) · 2.07 KB
/
Operation.java
File metadata and controls
65 lines (54 loc) · 2.07 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package calculator;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Operation {
private final String[] operation;
private List<Integer> operands;
private List<Character> operators;
public Operation(String input) {
this.operation = input.split(" ");
validateOperation();
splitOperation();
}
public void validateOperation() {
validateOtherSymbols();
validateFirstIndex();
validateDuplicate();
}
public void validateOtherSymbols() {
for (String tempStr : operation) {
if (!(tempStr.matches("^[0-9]*$") || tempStr.matches("^\\-[1-9]\\d*$") || tempStr.matches("[+*/-]")))
throw new IllegalArgumentException("한 String에 숫자와 연산자가 함께 있거나, 숫자 연산자 이외의 입력입니다.");
}
}
public void validateFirstIndex() {
if (operation[0].matches("[+*/-]")) {
throw new IllegalArgumentException("숫자로 시작해야 합니다.");
}
}
public void validateDuplicate() {
for (int i = 0; i < operation.length - 1; i++) {
if ((!operation[i].matches("[+*/-]") && !operation[i + 1].matches("[+*/-]"))
|| (operation[i].matches("[+*/-]") && operation[i + 1].matches("[+*/-]"))) {
throw new IllegalArgumentException("기호나 숫자가 두 번 연속 입력되었습니다.");
}
}
}
public void splitOperation() {
operands = Arrays.stream(this.operation)
.filter(operand -> operand.matches("^[0-9]*$") || operand.matches("^\\-[1-9]\\d*$"))
.map(Integer::parseInt)
.collect(Collectors.toList());
operators = Arrays.stream(this.operation)
.filter(operator -> operator.matches("[+*/-]"))
.map(operator -> operator.charAt(0))
.collect(Collectors.toList());
}
public List<Integer> getOperands() {
return operands;
}
public List<Character> getOperators() {
return operators;
}
}