0

Can someone point me into the right direction on how to make a function that allows the user to make calculations.

I'd like it to work as shown below:

java Calculate 8*8  
the answer = 64

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

The basic math operators are what I'd like to get working first, using parentheses is the next step.

Johan
  • 69
  • 2
  • 10

3 Answers3

2

You can use a 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]); 
}
Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63
assylias
  • 321,522
  • 82
  • 660
  • 783
1

Working code:

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);
    }
}
Johan
  • 69
  • 2
  • 10
0

Have a look here:

Is there an eval() function in Java?

You can pass arguments from the command line using the main method.

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
    }
}
Community
  • 1
  • 1
JeroenWarmerdam
  • 412
  • 2
  • 9