Write a program that evaluates an expression.assume the operands are integers and
operators are +, −, *, /.

Please help me.

7 Years
Discussion Span
Last Post by jon.kiparsky

Hey still learning myself but the four basic methods you need are

public int add(int num1, int num2)
    return num1 + num2;

public int subtract(int num1, int num2)
    return num1 - num2;

public int multiply(int num1, int num2)
    return num1 * num2;

public int divide(int num1, int num2)
    return num1 / num2;

Edited by Nick Evan: Fixed formatting


ok...But expression will be in string like 12+15/3+1*7...
there may arise some problem


now, actually, that's not as much a problem.
there are several ways you can do this.
the first is to use + - * / = as separators, and use the indexOf and substring method of string objects to get the numerical values.

an other way is to, char by char, extract the contents of the string and make a check eacht time whether or not the char is one of the separators.

what have you done yourself so far? it's better to try and fail, than to copy paste.


Very much thanks.....
I also believe better to try and fail than to copy paste but actually
am beginner in java(specially in such type of problems )..So please sir elaborate little bit more so that i could try and apply the concept myself..


Stutulske is right: your first problem is to work out what the component pieces of the expression are.

please elaborate little bit more

Let's start simple. Suppose you had a String, like
and you wanted to extract and print the integer part of that, so the output would be

- how would you do that? You don't have to write the program if you can describe how it would work.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.