-2

I have 2 variables an integer (Num1) and a String (Str1) My problem is that in the string I have stored a Sum eg: "3+3+3" And i need to convert it to the int (Num1). So my question is, is there a single method in java that i can use to do this

Code.

public class StringSum {
    public static void main(String[] args) {
        String Str1;
        int Num1 = 0;

        Str1 = "3+3+3";

        Num1 = Str; // Here is where i need the method

        System.out.println("The answer to " + Str1 + " is : " + Num1);
    }
}
Jordan
  • 3
  • 4

1 Answers1

1

Yes, you can use:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class Test {
  public static void main(String[] args) throws Exception{
    ScriptEngineManager manager= new ScriptEngineManager();
    ScriptEngine seng= manager.getEngineByName("JavaScript");
    String bar = "3+3+3";
    System.out.println(seng.eval(bar));
    } 
}

Using JavaScript engine

AMB
  • 995
  • 1
  • 12
  • 26