0

I'm trying to make a calculator where it's possible to either take in a single number, or take in a calculation (f.ex 2+2). Is it even possible to take in a calculation with scanner, or do some of you know a agile way to make it though.

System.out.println("Write in a number or a calculation: ");
Scanner a = new Scanner(System.in);
String ab = a.nextLine();
Double abc = Double.valueOf(ab);

I hoped that this would work, but as it converts from string to double, it crashes as there is a char.. Someone got any good ideas?

3 Answers3

0

Double.valueOf() is just a parser that knows to translate string that contains valid representation of double. It is not an interpreter that knows to evaluate mathematics expression.

To do this you can either implement such interpreter yourself or call JavaScript from java. You can find example here: Is there an eval() function in Java?

Community
  • 1
  • 1
AlexR
  • 114,158
  • 16
  • 130
  • 208
0

If you want to do everything with the Java API, you can do something like this.

System.out.println("Write in a number or a calculation: ");
Scanner a = new Scanner(System.in);
String ab = a.nextLine();
if(ab.contains("+")) {
    // parse the string
} else {
    Double abc = Double.valueOf(ab);
}

It would take a lot of work to get it working for all situations (the above is just a bad hardcoded way of checking if it's an addition), but it could work.

Refer to http://docs.oracle.com/javase/7/docs/api/java/lang/String.html for the different ways to manipulate/parse strings.

Troubleshoot
  • 1,816
  • 1
  • 12
  • 19
-1

You cannot do that directly as its in a String format,you can either use a Script engine ,or you can use the shunting yard algorithm to convert to postfix and then evaluate. The script engine syntax is

  ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine eng = manager.getEngineByName("JavaScript");
    String foo = "50+2";
    System.out.println(eng.eval(foo));