java calculator using nested expressions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jtanz0
    New Member
    • Jan 2008
    • 4

    #1

    java calculator using nested expressions

    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
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by jtanz0
    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.

    Comment

    • jtanz0
      New Member
      • Jan 2008
      • 4

      #3
      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

      Comment

      Working...