通过用户输入进行计算

时间:2012-09-15 12:01:08

标签: java math user-input

有人能指出我如何制作允许用户进行计算的功能的正确方向。

我希望它的工作方式如下所示:

java Calculate 8*8  
the answer = 64

java Calculate 7+(8*2)
the answer = 23

基本的数学运算符是我想要先工作的,下一步是使用括号。

3 个答案:

答案 0 :(得分:2)

您可以使用ScriptEngine

public static void main(String[] args) throws Exception {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    //pass in the string containing the operation, for example:
    double multiplication = (double) engine.eval(args[0]); 
}

答案 1 :(得分:1)

工作代码:

import javax.script.*;
import java.util.Scanner;
public class Test   {

    public static void main(String[] args) throws Exception 
    {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your calculation: ");
        String userInput = in.next();
        //pass in the string containing the operation, for example:
        double calculation = (Double) engine.eval(userInput); 
        System.out.print("The answer = " + calculation);
    }
}

答案 2 :(得分:0)

看看这里:

Is there an eval() function in Java?

您可以使用main方法从命令行传递参数。

public class Calculate{
    public static void main(String... args){
        if(args.length == 0){
            System.err.println("You forgot to add a formulate to run");
            return;
        }
        String formula = args[0];
        // Insert the formula into code from the link mentioned above
    }
}