-4

I am trying to get something like this to work

String s="3+33";
int i = Integer.parseInt(s);
String s2= Integer.toString(i);
System.out.println(s2);

However, it gives me NumberFormatException. Is there any workaround for this?

RaptorRV
  • 55
  • 1
  • 9
  • 1
    Obviously, `3+33` is not a valid integer literal. What do you try to achieve? – Henry May 31 '20 at 07:20
  • 1
    `3+33` is not a valid integer string. `Integer.parseInt` don't evaluate expression – Eklavya May 31 '20 at 07:21
  • Do you only want to support addition, or were you trying to make multiple types of math work? And how much do you want to write yourself, vs using built-in functionality? For example, `int v = (Integer) new ScriptEngineManager().getEngineByName("js").eval(s);` – Elliott Frisch May 31 '20 at 07:22
  • I am actually trying to develop a simple calculator where I read the input in the text field which is a string. Thus I was trying to convert it to int.Thats also why I converted it to string at the end – RaptorRV May 31 '20 at 07:41
  • @ElliottFrisch thanks the built-in functionality worked – RaptorRV May 31 '20 at 07:53

1 Answers1

0

There are a method in python, eval(), which can get the result of a string. For java you can use ScriptEngineManager for this purpose.

Please read this answer, it will help you a lot.

https://stackoverflow.com/a/2605051/10837115

Arif Akkas
  • 54
  • 6