0

I am new to Java so this may be a simple question.

I have made a calculator where the user clicks buttons and it enters the text into a JTextField.

I have used the .getText() method and saved it into a String.

Using System.out.println() I have seen that the String is "8*7*7-8/4", obviously if I could just execute this and get the answer 390 then this would be far easier than splitting it up and making it more complicated than it seems.

Thanks Matt

Bonifacio2
  • 3,405
  • 6
  • 34
  • 54

3 Answers3

1

You can actually evaluate the expression "8*7*7-8/4" directly using the built-in Java script engine. Have a look at this post.

Also have a look at this codereview post that explains some good points on how to evaluate a math expression present in a string.

Community
  • 1
  • 1
anirudh
  • 4,116
  • 2
  • 20
  • 35
  • I am referring to the `javax.script.ScriptEngineManager` and `javax.script.ScriptEngine` classes as shown in the link to the post I have given. Its built-in in JDK 1.6. – anirudh Apr 03 '14 at 14:50
0

You could do this to get the value of a float from a string:

Float.valueOf(string);

So you could do this, whenever a user inputs a number:

//method when user inputs a number, the String input will be what the user adds
float number = Float.valueOf(input);

Also, you could do something like this:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String input = "40+2";
System.out.println(engine.eval(input));

Above code from: Evaluating a math expression given in string form

Community
  • 1
  • 1
Jojodmo
  • 23,357
  • 13
  • 65
  • 107
  • Hi I tried this and I got Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "3*6" – Matt.Pinder Apr 03 '14 at 14:56
  • @user3494178 The first code, `Float.valueOf(string);`, only works if your doing a single number, like `5.6`, or `8`. Stuff like `8 + 3` and `5.6 * 22.1` won't work here. Yet, the bottom code, with`ScriptEngineManager mgr = new ScriptEngineManager();` will evaluate expressions like `3 * 6`, or `8 + 5` for you – Jojodmo Apr 04 '14 at 03:42
0

Add jar file jav8-jsr223-win-amd64-0.6 to the classpath for Java8 or corresponding jar as per JDK version and write the below code

String val = "8*7*7-8/4";//make it to get from field.getText()

ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("JavaScript");
Object result = engine.eval(val);

System.out.println(result);
Karibasappa G C
  • 2,686
  • 1
  • 18
  • 27