How do I add two numbers within one string?
I have:
String a = "(x+x)";
String lb = "2";
String b = a.replace("x", lb);
int c = ?
it outputs 2+2
, how do I get it to add them together correctly into an integer?
How do I add two numbers within one string?
I have:
String a = "(x+x)";
String lb = "2";
String b = a.replace("x", lb);
int c = ?
it outputs 2+2
, how do I get it to add them together correctly into an integer?
While you can use a Java library to achieve this goal as mentioned in the comments, there is something built into Java since version 6 which may be useful (but maybe a little overkill). I suggest this not because I believe it's particularly efficient but rather as an alternative to using a library.
Use JavaScript:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
ScriptEngine jsRuntime = new ScriptEngineManager().getEngineByName("javascript");
String expression = "2+2"; //The expression you would to evaluate.
double result = (Double) jsRuntime.eval(expression);
Use the Integer.parseInt
method to parse a String
into an int
, then add the values. Adding strings just concatenates them.
It seems your question could be summarised as
How do I convert a String such as
"2+2"
to the number4
Here's a solution that uses only the standard Java libraries:
String sumExpression = "2+2";
String[] numbers = sumExpression.split("\\+");
int total = 0;
for (String number: numbers) {
total += Integer.parseInt(number.trim());
}
// check our result
assert total == 4;