通过用户输入进行计算



有人能告诉我如何制作一个允许用户进行计算的函数吗。

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

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

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

您可以使用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]); 
}

工作代码:

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);
    }
}

看看这里:

Java中有eval()函数吗?

您可以使用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
    }
}

相关内容

  • 没有找到相关文章

最新更新