|  | 
|  | 1 | +package com.wonu606.calculator.validator; | 
|  | 2 | + | 
|  | 3 | +import com.wonu606.calculator.model.Operator; | 
|  | 4 | +import java.util.ArrayList; | 
|  | 5 | +import java.util.List; | 
|  | 6 | + | 
|  | 7 | +public class InfixValidator implements Validator { | 
|  | 8 | + | 
|  | 9 | +    private static boolean isExpectedNumericPosition(int position) { | 
|  | 10 | +        return position % 2 == 0; | 
|  | 11 | +    } | 
|  | 12 | + | 
|  | 13 | +    @Override | 
|  | 14 | +    public boolean isValid(String expression) { | 
|  | 15 | +        String[] tokens = expression.split("\\s"); | 
|  | 16 | +        List<String> operators = getOperators(); | 
|  | 17 | + | 
|  | 18 | +        for (int i = 0; i < tokens.length; i++) { | 
|  | 19 | +            if (isInvalidToken(i, tokens[i], operators)) { | 
|  | 20 | +                return false; | 
|  | 21 | +            } | 
|  | 22 | +        } | 
|  | 23 | +        return true; | 
|  | 24 | +    } | 
|  | 25 | + | 
|  | 26 | +    private boolean isInvalidToken(int position, String str, List<String> operators) { | 
|  | 27 | +        if (isExpectedNumericPosition(position)) { | 
|  | 28 | +            return !isNumeric(str); | 
|  | 29 | +        } | 
|  | 30 | +        return !isOperator(operators, str); | 
|  | 31 | +    } | 
|  | 32 | + | 
|  | 33 | +    private List<String> getOperators() { | 
|  | 34 | +        List<String> operators = new ArrayList<>(); | 
|  | 35 | +        for (Operator operator : Operator.values()) { | 
|  | 36 | +            operators.add(operator.symbol); | 
|  | 37 | +        } | 
|  | 38 | +        return operators; | 
|  | 39 | +    } | 
|  | 40 | + | 
|  | 41 | +    private Boolean isNumeric(String str) { | 
|  | 42 | +        try { | 
|  | 43 | +            Double.parseDouble(str); | 
|  | 44 | +        } catch (NumberFormatException e) { | 
|  | 45 | +            return false; | 
|  | 46 | +        } | 
|  | 47 | +        return true; | 
|  | 48 | +    } | 
|  | 49 | + | 
|  | 50 | +    private boolean isOperator(List<String> operators, String expectedOperator) { | 
|  | 51 | +        return operators.contains(expectedOperator); | 
|  | 52 | +    } | 
|  | 53 | +} | 
0 commit comments