[SOLVED] Evaluating an Airthmetic Expression
I need to write a Java program, which reads and Airthmetic Expression and evaluates it.
I have done some part of the program, using classes, but got stuck in coding the Evaluation method. But let me admit that I do have some idea of evaluating the inputted expression.
NOTE: Its assumed that user always enters valid expression and the expression has only *,/,+ and - operators only.
I am reading a valid arithmetic expression and looking for the first occurrence of * or / sign and then from that index I am taking the string on the left side of the sign and string to right side of the sign.
Then in Left String I am looking for the lastindexOf( ) function which will give me the last occurrence of the + or - sign(since from the precedence rule Multiplication/Division is first and then + -)
And on the Right side I am looking for indexOf( ) string function which will give me the index of the first occurrence of the operator + , - , / or * . Based on these two left and right indices I am extracting two operands and one operator(either * or / whichever comes first) and performing the operation between them and will update the string with this operation result.
I will be doing this till my expression has only + and - operators and then at the end I can evaluate the string.
But now what I did, is very long and its not even giving the required result.
I will really appreciate if any one can help me with this.
Help with Evaluatig an Airthmetic expression code
Can any body help me with this execution error???
I have written this program, but it shows me an error saying that "} is expected", though I have put all brackets properly.
this is my code:
private String e;
e = "";
e = s;
/*public void set(String s)
e = s;
public void print()
public int evaluate()
int n1=0, n2=0;
int op1 = -1, op2 = -1;
for(int i=0; i<e.length(); i++)
if(e.charAt(i)=='*' ||e.charAt(i) =='/' ||e.charAt(i)=='#')
String eleft = e.substring(0,i);
String eright = e.substring(i+1, e.length());
op1 = eleft.lastIndexOf('+');
op2 = eright.lastIndexOf('-');
if(op1 > op2)
n1 = Integer.parseInt(eleft.substring(op1+1, i));
n2 = Integer.parseInt(eleft.substring(op2+1, i));
for(int k = 0; k < eright.length()-1; k++)
if(eright.charAt(k)== '+' || eright.charAt(k)== '-' ||eright.charAt(k)== '*' || eright.charAt(k)== '/' ||eright.charAt(k)== '#')
String erightNum = eright.substring(0, k);
n2 = Integer.parseInt(erightNum);
n1 = n1 * n2;
else if(e.charAt(i) =='/')
n1 = n1 / n2;
public static void main(String  args)
Scanner keyin = new Scanner(System.in);
System.out.println("Please Enter a valid Airthmetic Expression followed by #:");
str = keyin.next();
AirthExp expStr = new AirthExp(str);