424,303 Members | 1,339 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,303 IT Pros & Developers. It's quick & easy.

java calculator using nested expressions

P: 4
Im fairly new to java programming although i have some experience in python.

I have to create a calculator program (command line) which takes as input a mathematical expression consisting of decimal numbers and the four basic mathematical operators (+,-,/,*) and correctly handles nested mathematical expressions.

Some examples:
5 + 6 * 2 results in 17
(5 + 4) * (4 - 2) results in 18

i can do the basics ie taking an input and getting answers from simple maths expressions. but i am having trouble coming up with a way to sort out the nested expressions, my current thinking is to either put the input string into an array list and cycle through putting the expressions in a stack based on finding the characters "(" and ")" or possibly splitting the string first based on the same criteria then putting them into different collections but im unsure on whether this will work and how to sort out the ordering

if anyone can throw some light on how this might be implemented i would be very grateful

Thanks

Jon
Jan 31 '08 #1
Share this Question
Share on Google+
2 Replies


10K+
P: 13,264
Im fairly new to java programming although i have some experience in python.

I have to create a calculator program (command line) which takes as input a mathematical expression consisting of decimal numbers and the four basic mathematical operators (+,-,/,*) and correctly handles nested mathematical expressions.

Some examples:
5 + 6 * 2 results in 17
(5 + 4) * (4 - 2) results in 18

i can do the basics ie taking an input and getting answers from simple maths expressions. but i am having trouble coming up with a way to sort out the nested expressions, my current thinking is to either put the input string into an array list and cycle through putting the expressions in a stack based on finding the characters "(" and ")" or possibly splitting the string first based on the same criteria then putting them into different collections but im unsure on whether this will work and how to sort out the ordering

if anyone can throw some light on how this might be implemented i would be very grateful

Thanks

Jon
Have a read at Jos' compilers series.
Jan 31 '08 #2

P: 4
thanks!

I've been researching think im going to go for the approch of changing the input from infix to post fix as i have already done a RPN calculator in python and i understand how this works
Feb 3 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.