天天看點

自己寫的一個簡單的加法解釋器

package b.a.leetcode;

public class Intercepter {
    private Token currentToken;
    private int currentPosition;
    private String currentText;

    private Token getNextToken() {
        if (currentPosition > currentText.length() - 1) {
            return new Token(TokenType.EOF, -1);
        }
        char charAt = currentText.charAt(currentPosition++);
        if (Character.isDigit(charAt)) {
            return new Token(TokenType.INTEGER, charAt - '0');
        } else {
            return new Token(TokenType.PLUS, -1);
        }

    }


    public int expr(String text) {
        this.currentPosition = 0;
        this.currentText = text;
        currentToken = getNextToken();
        Token left = currentToken;
        eat(TokenType.INTEGER);
        Token plus = currentToken;
        eat(TokenType.PLUS);
        Token right = currentToken;
        eat(TokenType.INTEGER);
        return left.value + right.value;

    }

    private void eat(TokenType integer) {
        if (currentToken.getType() == integer) {
            currentToken = getNextToken();
        }
    }

    public static void main(String[] args) {
        Intercepter intercepter = new Intercepter();
        int expr = intercepter.expr("1+6");
        System.out.print(expr);
    }
}
           

繼續閱讀