I have a String that is called for example str="3+5-4+4+5"; i can split it using split(); method but how can i calc more than 2 number like this string
Asked
Active
Viewed 168 times
-1
-
Did you try `System.execute("calc.exe", "3+5-4+4+5");` – vikingsteve Aug 22 '14 at 12:29
4 Answers
2
You may try this:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
String str = "3+5-4+4+5";
public void myStringCalculation(String str)
{
ScriptEngineManager x = new ScriptEngineManager();
ScriptEngine e = x.getEngineByName("JavaScript");
System.out.println(e.eval(str));
}

Rahul Tripathi
- 168,305
- 31
- 280
- 331
-
-
-
@Conffusion:- Yes. I added that as I thought it will make more clarity :) – Rahul Tripathi Aug 22 '14 at 12:47
-
@RT: and you completely changed the code too. I could not find an `Interpreter` class which was in your initial post. – Conffusion Aug 22 '14 at 12:50
-
1
0
You can do it like this :
- Fetch the numbers
- Identify the operator
- Perform the operation as per the operator for two selected number.

Vimal Bera
- 10,346
- 4
- 25
- 47
0
Look at this SO link - there are ready-to-go parsers out there which will interpret a mathematical expression and return the result of it.

Community
- 1
- 1

Axel Amthor
- 10,980
- 1
- 25
- 44
0
I assume you want to experiment coding.
You might reduce the expression as long as possible using reducible expressions of the form number operator number
.
Here a simple version for binary operators, no braces, no negative numbers, only.
String[] operators = new String[] {
"*", "/",
"+", "-"
};
String expr = "3+5-4+4+5";
for (;;) {
boolean reduced = false;
for (String op : operators) {
Pattern redex = Pattern.compile("(\\d+)" + Pattern.quote(op) + "(-?\\d+)");
Matcher m = term.matcher(expr);
StringBuffer sb = new StringBuffer();
while (m.find()) {
int lhs = Integer.parseInt(m.group(1));
int rhs = Integer.parseInt(m.group(2));
int y = 0;
switch (op) {
case "*": y = lhs * rhs; break;
case "/": y = lhs / rhs; break;
case "+": y = lhs + rhs; break;
case "-": y = lhs - rhs; break;
default: throw new IllegalStateException("Not implemented: " + op);
}
m.appendReplacement(sb, String.valueOf(y));
reduced = true;
}
m.appendTail(sb);
expr = sb.toString();
}
if (!reduced) {
break;
}
}
Negative numbers could function with (negative) look-ahead/behind in the regex.

Joop Eggen
- 107,315
- 7
- 83
- 138