判断书否是算数表达式--Java

判断书否是算数表达式--Java,第1张

判断书否是算数表达式--Java
public static boolean isTrueexpression(String expression) {
        if (isOperator(expression.charAt(0)) || isOperator(expression.charAt(expression.length() - 1)) || isPoint(expression.charAt(0)) || isPoint(expression.charAt(expression.length() - 1))) {
            return false;
        } else {
            int countLeft = 0;
            int countRight = 0;
            boolean after = true;
            for (int i = 0; i < expression.length(); i++) {
                char ch = expression.charAt(i);
                if (isNumber(ch) || isOperator(ch) || isPoint(ch) || isBracket(ch)) {
                    if (ch == '(') {
                        countLeft++;
                    }
                    if (ch == ')') {
                        countRight++;
                    }
                    if (ch == '/') {
                        if (expression.charAt(i + 1) == '0') {
                            after = false;
                            return false;
                        }
                    }
                    if (isNumber(ch)) {
                        if (i != expression.length() - 1 && isBracket(expression.charAt(i + 1))) {
                            after = false;
                            return false;
                        }
                    }
                    if (isOperator(ch)) {
                        if (isPoint(expression.charAt(i - 1)) || isPoint(expression.charAt(i + 1))) {
                            after = false;
                            return false;
                        }
                    }
                    if (isPoint(ch)) {
                        if (!isNumber(expression.charAt(i - 1)) || !isNumber(expression.charAt(i + 1))) {
                            after = false;
                            return false;
                        }
                    }
                } else {
                    after = false;
                    return false;
                }
            }
            if (after) {
                if (countLeft != countRight) {
                    return false;
                } else {
                    return true;
                }
            }
        }
        return true;
    }

    public static boolean isNumber(char ch) {
        if (ch >= '0' && ch <= '9') {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isOperator(char ch) {
        if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isPoint(char ch) {
        return ch == '.';
    }

    public static boolean isBracket(char ch) {
        return ch == '(' || ch == ')';
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5081820.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存