-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathExpressionValidator.java
More file actions
55 lines (44 loc) · 1.75 KB
/
ExpressionValidator.java
File metadata and controls
55 lines (44 loc) · 1.75 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
package domain.calculator;
import domain.calculator.exception.InvalidInputException;
import java.util.List;
import java.util.regex.Pattern;
public class ExpressionValidator {
public void validateTokenList(List<String> tokenList) {
long invalidTokenCount = tokenList.stream()
.filter(token -> !isNumber(token) && !isOperator(token))
.count();
if (invalidTokenCount > 0) {
throw new InvalidInputException("올바르지 않은 입력입니다.");
}
}
public void validateTokenSequence(List<String> tokenList) {
throwIfConditionIsTrue(hasNotAnyToken(tokenList));
String firstToken = tokenList.get(0);
throwIfConditionIsTrue(!isNumber(firstToken));
for (int i = 1; i < tokenList.size(); i += 2) {
String operatorToken = tokenList.get(i);
throwIfConditionIsTrue(!isOperator(operatorToken));
if (isNotLastOperation(i, tokenList.size())) {
String rightOperandToken = tokenList.get(i + 1);
throwIfConditionIsTrue(!isNumber(rightOperandToken));
}
}
}
private void throwIfConditionIsTrue(boolean isConditionTrue) {
if (isConditionTrue) {
throw new InvalidInputException("올바르지 않은 입력입니다.");
}
}
private boolean hasNotAnyToken(List<String> tokenList) {
return (tokenList.size() == 0);
}
private boolean isNumber(String token) {
return Pattern.matches("^[0-9]+$", token);
}
private boolean isOperator(String token) {
return Pattern.matches("\\+|-|\\*|/", token);
}
private boolean isNotLastOperation(int index, int tokenListSize) {
return (index + 1 < tokenListSize);
}
}