有人可以指出我如何制作一个允许用户进行计算的函数的正确方向。
我希望它如下所示工作:
java Calculate 8*8
the answer = 64
java Calculate 7+(8*2)
the answer = 23
基本的数学运算符是我想首先使用的,下一步是使用括号。
有人可以指出我如何制作一个允许用户进行计算的函数的正确方向。
我希望它如下所示工作:
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);
}
}
看看这里:
您可以使用 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
}
}