Note that there are some explanatory texts on larger screens.

plurals
  1. POEvaluate a Math Expression given in string form without using API
    text
    copied!<p>I want to evaluate an expression like <code>-4-12-2*12-3-4*5</code> given in a <code>String</code> form <strong>without using API</strong> as I am a beginner and want to grasp the logic.</p> <p>Given below is my unsuccessful attempt to this problem which, if you may like, ignore and suggest appropriate logic.And of course your codes are also welcome :-)</p> <pre><code>public class SolveExpression3 { static String testcase1 = "-4-12-2*12-3-4*5"; public static void main(String args[]){ SolveExpression3 testInstance= new SolveExpression3(); int result = testInstance.solve(testcase1); System.out.println("Result is : "+result); } public int solve(String str){ int sum = 1; int num1 = 0; int num2 = 0; String num = ""; int len = str.length(); System.out.println(str); for (int i = len-1 ; i &gt;= 0; i--) { char ch = str.charAt(i); if(ch == '*') { String s = ""; num1 = num2 = 0; //to get the number on left of * for (int j = i; j &gt;= 0; j--) { char c = str.charAt(j); if(c == '+' || c == '-' || j == 1) { num1 = stringToInt(s); s = ""; break; } else { s = c + s; } } //to get the number on right of * for (int j = i; j &lt;= len; j++) { char c = str.charAt(j); if(c == '+' || c == '-' || j == len-1) { num2 = stringToInt(s); s = ""; break; } else { s = c + s; } } sum = sum + num1*num2; } else { num = ch + num; } } len = str.length(); for (int i = len-1; i &gt;= 0; i--) { char ch = str.charAt(i); if(ch==' ') {} else if(ch=='+') { sum = sum + stringToInt(num); num = ""; } else if(ch=='-') { sum = sum - stringToInt(num); num = ""; } else { num = ch + num; } } return sum; } public int stringToInt(String str) { int number=0; for(int i = 0; i &lt; str.length(); i++) { int num = str.charAt(i) - 48; number = number*10+num; } return number; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload