programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Calculating an Arithmetic Expression

Kaspersky Ukshini
Ranch Hand
Posts: 122
Hey guys, me again!
First of all I'd like to thank you all for helping me out preparing my exam, I believe I'm doing great and I'm deeling more confident each day!!! THANK YOU AGAIN !!

My next problem is an Arithmetic Expression.

I have a given arithmetic expression, which form is (A+B) or (A-B), were A and B are either numbers from 0-9, or another ARITHMETIC Expression.
The first thing that comes to my mind is a recursive function, but no idea how to start... Can someone give me a hand please?

Janeice DelVecchio
Bartender
Posts: 1812
12
Is it always addition or subtraction?

The reason I ask is because multiplication/division have precedence.

Kaspersky Ukshini
Ranch Hand
Posts: 122
Hey mate,

No, the arithmetic expression doesn't have other operations other than + or - ..

Its (A+B) OR (A-B)
A - can be a number from 0-9 OR it can be another expression (A+B) OR (A-B) and so on and so on...

Same goes for B.

Janeice DelVecchio
Bartender
Posts: 1812
12
then why not just strip out the parens from the input and just add or subtract as you go left to right, reading each number or operation one at a time?

fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Janeice DelVecchio wrote:then why not just strip out the parens from the input and just add or subtract as you go left to right, reading each number or operation one at a time?

5 - (3 + 4)

is very different from

5 - 3 + 4

Janeice DelVecchio
Bartender
Posts: 1812
12
Math is hard. ;)

I guess you could use a stack then.
http://www.smccd.net/accounts/hasson/C++2Notes/ArithmeticParsing.html

A close without an open would break it though. So one would need to validate if you got a close, you already have the open. Maybe you need a third stack for the parens. Or just keep track with a Boolean.

Janeice DelVecchio
Bartender
Posts: 1812
12
And a stack in java, to me, is the same as a Queue. My mind is muddied from learning perl long ago.

fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
• 1
Janeice DelVecchio wrote:Math is hard. ;)

LOL