繁体   English   中英

获取Java程序以读取括号,方括号和花括号

[英]Get the Java program to read parenthesis, brackets, and curly braces

我正在编写一个程序,以验证算术表达式是否正确形成。 (例如:正确的格式"2 + (2-1)" ,错误的格式")2+(2-1"

验证之后,程序将计算结果。

目前,它可以轻松地计算括号中的任何内容。 但是,如果涉及到方括号(例如, "2 [ 3 + (1) ]" ),则程序将验证表达式是否正确,但无法计算结果。

这是我关注的代码

void postfixExpression() {
    stk.clear(); // Re-using the stack object
    Scanner scan = new Scanner(expression);
    char current;
    // The algorithm for doing the conversion.... Follow the bullets
    while (scan.hasNext()) {
        String token = scan.next();

        if (isNumber(token)) 
        {
            postfix = postfix + token + " ";
        } else {
            current = token.charAt(0);

            if (isParentheses(current))
            {
                if (stk.empty() || current == Constants.LEFT_NORMAL) {

                    // push this element on the stack;
                    stk.push(new Character(current));
                } else if (current == Constants.RIGHT_NORMAL) {
                    try {

                        Character ch = (Character) stk.pop();
                        char top = ch.charValue();

                        while (top != Constants.LEFT_NORMAL) {
                            postfix = postfix + top + " ";
                            ch = (Character) stk.pop();
                            top = ch.charValue();
                        }

                    } catch (EmptyStackException e) {

                    }
                }
            } else if (isOperator(current))//
            {
                if (stk.empty()) {
                    stk.push(new Character(current));
                } else {
                    try {


                        char top = (Character) stk.peek();
                        boolean higher = hasHigherPrecedence(top, current);

                        while (top != Constants.LEFT_NORMAL && higher) {
                            postfix = postfix + stk.pop() + " ";
                            top = (Character) stk.peek();
                        }
                        stk.push(new Character(current));
                    } catch (EmptyStackException e) {
                        stk.push(new Character(current));
                    }
                }
            }// Bullet # 3 ends

        }
    } // Outer loop ends

    try {
        while (!stk.empty()) // Bullet # 4
        {
            postfix = postfix + stk.pop() + " ";
        }
    } catch (EmptyStackException e) {

    }
 }

我创建了两个方法:isBracket和isCurly。 起初,我认为最合适的解决方案是仅以与isParentheses相同的方式包括这两种方法。 像这样:

 if (isParentheses(current))
            {
                if (stk.empty() || current == Constants.LEFT_NORMAL) {

                    // push this element on the stack;
                    stk.push(new Character(current));
                } else if (current == Constants.RIGHT_NORMAL) {
                    try {

                        Character ch = (Character) stk.pop();
                        char top = ch.charValue();

                        while (top != Constants.LEFT_NORMAL) {
                            postfix = postfix + top + " ";
                            ch = (Character) stk.pop();
                            top = ch.charValue();
                        }

                    } catch (EmptyStackException e) {

                    }
                }

            if (isCurly(current)) 
            {
                if (stk.empty() || current == Constants.LEFT_CURLY) {

                    // push this element on the stack;
                    stk.push(new Character(current));
                } else if (current == Constants.RIGHT_CURLY) {
                    try {

                        Character ch = (Character) stk.pop();
                        char top = ch.charValue();

                        while (top != Constants.LEFT_CURLY) {
                            postfix = postfix + top + " ";
                            ch = (Character) stk.pop();
                            top = ch.charValue();
                        }

                    } catch (EmptyStackException e) {


 if (isBracket(current)) 
            {
                if (stk.empty() || current == Constants.LEFT_SQUARE) {

                    // push this element on the stack;
                    stk.push(new Character(current));
                } else if (current == Constants.RIGHT_SQUARE) {
                    try {

                        Character ch = (Character) stk.pop();
                        char top = ch.charValue();

                        while (top != Constants.LEFT_SQUACRE) {
                            postfix = postfix + top + " ";
                            ch = (Character) stk.pop();
                            top = ch.charValue();
                        }

                    } catch (EmptyStackException e) {

但是该程序仍然不会考虑括号和花括号(但仍可以很好地读取括号)。

根据我的理解,我没有正确使用这些方法,但是如何正确使用它们呢?

这是我想到的一种解决此问题的方法。

您可以将数字和方括号分为两个不同的堆栈,从而更容易确保表达式正确地形成。

在代码的开头,您可以声明两个堆栈变量:

Stack<Integer> numbers = new Stack<Integer>();
Stack<Character> operators = new Stack<Character>();

然后相应地推运算符和数字。

我创建的这个非常快速的方法将演示使用两个Stack对象的实现:

public double doCalculation(String input) throws DataFormatException {
    if (input == null) {
        return 0;
    }

    char[] characters = input.toCharArray();

    for (char character: characters) {
        try {
            // tries to push the number onto the number stack
            numbers.push(Integer.parseInt("" + character));

        } catch (NumberFormatException e1) {
            // if this is caught, this means the character is non-numerical
            operators.push(character);

        }
    }

    while (operators.size() > 0) {
        int i = numbers.pop();
        int j = numbers.pop();
        char operator = operators.pop();

        switch (operator) {
            case '+':
                numbers.push(j + i);
                break;
            case '-':
                numbers.push(j - i);
                break;
            case '*':
                numbers.push(j * i);
                break;
            case '/':
                numbers.push(j / i);
                break;
            case '^':
                numbers.push((int)(Math.pow(j, i)));
                break;
            default:
                throw new DataFormatException();
        }
    }

    return numbers.pop();
}

只是为了好玩:如果在将非数字字符压入堆栈之前将此代码添加到catch块中,它将按照操作顺序来计算等式:

char top;
try {
    top = operators.peek();
} catch (EmptyStackException e2) {
    operators.push(character);
    continue;
}

if (getValue(character) > getValue(top)) {
    operators.push(character);
    continue;
} else {
    try {
        while (!(getValue(character) > getValue(operators.peek()))) {
            char operator;

            operator = operators.pop();

            int i = numbers.pop();
            int j = numbers.pop();

            switch (operator) {
                case '+':
                    numbers.push(j + i);
                    break;
                case '-':
                    numbers.push(j - i);
                    break;
                case '*':
                    numbers.push(j * i);
                    break;
                case '/':
                    numbers.push(j / i);
                    break;
                case '^':
                    numbers.push((int)(Math.pow(j, i)));
                    break;
                default:
                    throw new DataFormatException();
            }

        }
    } catch (EmptyStackException e3) {
        operators.push(character);
        continue;
    }

假设相应地定义了getValue()方法:

public int getValue(char character)
throws DataFormatException {
    switch (character) {
        case '+':
            return 1;
        case '-':
            return 1;
        case '*':
            return 2;
        case '/':
            return 2;
        case '^':
            return 3;
        default:
            throw new DataFormatException();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM