-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);
    }
}
0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked
@YELLOWKIGHT Nice!, if you have one moment please accept the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.