解析运算符和操作数

时间:2015-04-24 02:12:37

标签: java

好的,所以我正在写一个控制台计算器而且我被卡住了。我有一切正常,但用户输入的实际部分说3 * 2 + 8然后程序告诉用户答案。但是,我可以输入一个像3这样的数字,它返回3.0。我想我需要解析用户输入的表达式来执行数学运算。你能帮助我吗?

    public static void main(String[] args) {
        String input = ""; // initalize the string
        boolean isOn = true; // used for the while loop...when false, the program will exit.
        String exitCommand = "Exit"; // exit command



        System.out.print("Enter a math problem"); // dummy test
        Scanner keyboard = new Scanner(System.in);
        //input = keyboard.nextLine();
        String[] token = input.split(("(?<=[-+*/])|(?=[-+*/])"));
        while (isOn) {
            for (int i = 0; i < token.length; i++) {
                //System.out.println(token[i]);
                Double d = Double.parseDouble(keyboard.nextLine()); //This causes an error
                //String[] token = d.split(("(?<=[-+*/])|(?=[-+*/])"));
                //input = keyboard.nextLine();

                if (input.equalsIgnoreCase(exitCommand)) {
                    // if the user enters exit(ignored case) the boolean goes to false, closing the application
                    isOn = false;
                }

               System.out.print(token[0] + d); // shows the math problem(which would by the end of the coding should show the
                //answer to the entered math problem.

            }


        }
    }
    public void validOperator() {
        ArrayList<String> operator = new ArrayList<String>();
        operator.add("+");
        operator.add("-");
        operator.add("*");
        operator.add("/");

    }
    public void validOperands(){
        ArrayList<String> operand = new ArrayList<String>();
        operand.add("0");
        operand.add("1");
        operand.add("2");
        operand.add("3");
        operand.add("4");
        operand.add("5");
        operand.add("6");
        operand.add("7");
        operand.add("8");
        operand.add("9");
    }
}

由于

1 个答案:

答案 0 :(得分:1)

您没有考虑数学运算符的优先级。如果用户使用括号,例如(2 + 3) * 4 + 5/2

,该怎么办?

我建议在评估之前将初始表达式转换为postfix notation

以下是the example with explanation for C++,我认为将此解释应用于java语言会很容易。