有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将变量(字母)输入计算器类函数

这是密码 我有一个计算器类,现在它只计算数字,但我试图让它计算一个变量,并将变量的值设置为一个特定的数字,即5

对不起,我不清楚。当我运行这个计算器,输入1+1,它会给我2作为答案。但我希望能够包括一个变量,例如3*x^2或3*y^2。变量的值为5。现在这个代码无法做到这一点

public class Calculator {

    // Allowable mathematical operators
    static final String operators = "+-*/%()^!";

    private String strPostfix;
    private String strInfix;
    private char chrVariable;
    private int intError;

    /**
     * Default constructor. Sets all local values to default values
     */
    public Calculator() {
        setEquation("");
    }

    /**
     * Sets a new equation.
     * @param equation The new equation.
     * @remarks Note that this also resets all values stored same as creating a new object
     */
    public void setEquation(String equation)
    {
        // Remove any spaces, as they aren't necessary 
        strInfix = equation.replace(" ", "").trim();
        strPostfix = "";
        chrVariable = '\0';
        intError = -2;
    }

    /**
     * Gets the character location of the error found. -1 means no error found.
     * @return An integer specifying the location of the error. 
     */
    public int get_ErrorLocation()
    {
        return intError + 1;
    }

    /**
     * Gets the operators being used 
     * @return The operators
     */
    public String get_Operators()
    {
        return operators;
    }

    /**
     * Gets the post fix equation stored in memory for this object
     * @return A post fix equation stored in a string
     */
    public String get_PostFix()
    {
        return strPostfix;
    }

    /**
     * Gets the variable that is in the equation. '~' means no variable found.
     * @return The variable being used in the equation. 
     */
    public char get_Variable()
    {
        return chrVariable;
    }

    /**
     * Solves the equation stored in memory for this instance, and stores it in memory
     * @return A solution to a pre-existing equation
     * @throws NoEquationException Occurs when attempting to solve an equation that doesn't exist
     * @throws DivisionByZeroException Thrown when attempting to divide by zero
     * @throws InvalidEquationException Occurs if an equation is invalid for an undefined reason
     * @throws ExistingVariableException Occurs when attempting to use two variables
     * @throws InvalidCharacterException Occurs when an invalid character is entered
     */
    public double Solve() throws NoEquationException, DivisionByZeroException, InvalidEquationException, InvalidCharacterException, ExistingVariableException
    {
        strPostfix = PostFix().trim();
        System.out.println(strPostfix);

        return SolvePost();
    }

    /**
     * Determines the precendence of a give mathematical operator
     * @param value The mathematical operator
     * @return The precendence of the operator
     */
    private short precedence(char value) {
        switch (value) {
        case '+':
        case '-':
            return 1;
        case '*':
        case '/':
        case '%':
            return 2;
        case '!':
            return 3;
        case '^':
            return 4;
        default:
            return -1; 
        }
    }


    /**
     * Turns an infix equation into post-fix
     * @return The post-fix equivalent of the equation
     * @throws InvalidEquationException When an invalid equation is given
     * @throws ExistingVariableException Occurs when attempting to use two variables
     * @throws InvalidCharacterException Occurs when an invalid character is entered
     * @throws NoEquationException Occurs when attempting to solve an equation that doesn't exist
     */
    private String PostFix() throws InvalidEquationException, InvalidCharacterException, ExistingVariableException {
        // Backup the equation
        String infix = strInfix;

        String postfix = "";
        char current;
        char chrVariable;
        Stack<Character> stack = new Stack<Character>();
        boolean hasDec = false;

        // For every character in the string



        for ( int idx = 0; idx < infix.length(); ++idx ) {
            current = infix.charAt(idx);







            // If it is a digit or letter , just add it to postfix
            if ( Character.isDigit(current) ) {
                postfix += current;





            // If it is a decimal, make sure there is only one per number

            }else if (Character.isLetter(current))
                postfix+=current;

            else if( current == '.' ) {
                if (!hasDec) 
                    postfix += String.valueOf(current);

                else 
                    throw new InvalidEquationException();

                hasDec = true;



            // Otherwise, its an operator
            } 
            else {
                postfix += " ";
                hasDec = false;
                char peek;
                // If there's an opening brace, just push it to the stack
                if ( current == '(' )
                    stack.push(current);
                // If its a closing brace, find pop until you find the opening one
                else if ( current == ')' ) {
                    while ( !stack.isEmpty() && stack.peek() != '(' ) {
                        postfix += stack.pop() + " ";
                    }
                    // If the stack is empty, '(' was not found, error
                    if (stack.isEmpty()) { throw new InvalidEquationException('('); }
                    // Remove the '(' from the list
                    stack.pop();
                } else {
                    if ( current == '-' && ( idx == 0 || operators.contains(String.valueOf(infix.charAt(idx - 1)))))  {
                                postfix += current;
                    } else {
                        short prec = precedence(current);
                        if ( prec == -1 ) {
                            intError = idx;
                            throw new InvalidCharacterException();
                        }
                        // Pop off everything that has greater or equal precedence 
                        if ( !stack.isEmpty() ) {
                            peek = stack.peek();
                            while ( precedence(current) <= precedence(peek) ) {
                                postfix += stack.pop() + " ";
                                if ( !stack.isEmpty() ) 
                                    peek = stack.peek();
                                else
                                    break;
                            }
                        }
                        // Now add the current onto the stack
                        stack.push(current);
                    }
                }
            }
        }

        // Finally, empty out the stack
        while ( !stack.isEmpty() ) {
            postfix += " " + stack.pop();
        }

        postfix = postfix.trim();
        while ( postfix.contains("  ") ) {
            postfix = postfix.replaceAll("  ", " ");
        }

        return postfix;
        }




    /**
     * Solves the post-fix equation
     * @return The solution to the equation
     * @throws NoEquationException Thrown when PostFix equation not set
     * @throws DivisionByZeroException Thrown when attempting to divide by zero
     * @throws InvalidEquationException When an invalid equation is given
     */
    private double SolvePost() throws NoEquationException, DivisionByZeroException, InvalidEquationException {
        // Make sure there is an equation to solve


        if ( strPostfix.trim().isEmpty() )
            throw new NoEquationException();

        Stack<Double> stack = new Stack<Double>();
        String tokens[] = strPostfix.split(" "); 

        for ( String current : tokens ) {
            try {
                // If its a number, just push it
                stack.push(Double.parseDouble(current));

            } catch (Exception e) {
                // If its not an operator, there's a problem
                if ( current.length() > 1 || !operators.contains(current) )

                    throw new InvalidEquationException();

                // there must be two operands, otherwise there's a problem
                double first = 0, second = 0;
                try {
                    second = stack.pop();
                    if ( current.charAt(0) != '!' )
                        first = stack.pop();
                } catch (Exception ex) {
                    throw new InvalidEquationException();
                }

                // Do the appropriate math
                switch ( current.charAt(0) ) {
                case '+':
                    stack.push(first + second);
                    break;
                case '-':
                    stack.push(first - second);
                    break;
                case '*':
                    stack.push(first * second);
                    break;
                case '/':
                    // Make sure its not division by zero
                    if (second == 0) { throw new DivisionByZeroException(); }
                    stack.push(first / second);
                    break;
                case '%':
                    stack.push(first % second);
                    break;
                case '^':
                    stack.push(Math.pow(first, second));
                    break;
                case '!':
                    if ( (int)second != second || second < 0 )
                        throw new InvalidEquationException();
                    int result = 1;
                    for ( int i = 2; i <= second; ++i )
                        result *= i;
                    stack.push((double)result);
                    break;
                default:
                    // Anything else isn't valid
                    throw new InvalidEquationException(); 
                }
            }
        }

        return stack.pop();
    }
}

共 (0) 个答案