-1

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?

metelofe
  • 23
  • 1
  • 1
  • 3
  • 3
    What's the issue in using it as a integer itself? Instead of putting it in String and trying to convert it back to integer. – Pradeep Simha Oct 10 '13 at 17:08
  • 1
    Do you want to execute '2+2' string? – bsiamionau Oct 10 '13 at 17:10
  • 6
    possible duplicate of [free Java library for evaluating math expressions](http://stackoverflow.com/questions/7258538/free-java-library-for-evaluating-math-expressions) – Luiggi Mendoza Oct 10 '13 at 17:10
  • It almost sounds like OP might be trying to implement some sort of evaluator for arithmetic expressions, perhaps unintentionally. In his example, he is printing the string "(2+2)" and expecting it to print "4". He might also be confused about String and integer types, but I wanted to throw out another possible explanation in case someone wants to expand on it. – William Brendel Oct 10 '13 at 17:12
  • `int lb = 2; System.out.println( "" + lb + "+" + lb ); System.out.println( lb+lb );` – clcto Oct 10 '13 at 17:13

4 Answers4

1

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);
sushain97
  • 2,752
  • 1
  • 25
  • 36
0

Use the Integer.parseInt method to parse a String into an int, then add the values. Adding strings just concatenates them.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

You can use parseInt() method.

DT7
  • 1,615
  • 14
  • 26
0

It seems your question could be summarised as

How do I convert a String such as "2+2" to the number 4

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;
Dónal
  • 185,044
  • 174
  • 569
  • 824