• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to evaluate a string like " 3 + 4 / 3 - 2" ?  RSS feed

 
Adsf Badf
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



How to evaluate  a string like " 3 + 4 / 3 - 2"  ?

i would like to get the numerical answer to the string using the correct BEDMAS notation.
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Is it a homework?

There is a very quick way of doing it, but probably wouldn't be a good idea for homework.
There is another way, which you'd need to come up with - with our help possibly.

Latter way is harder.
 
Adsf Badf
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


i tried to hard code  a string with a mathematical expression and parse it into a number called num1 and display the answer.

hc is the button which runs the event once clicked.
ans is the answer text field.









but I keep getting this error:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "3+4/2"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Frame1$5.actionPerformed(Frame1.java:162)
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but I keep getting this error:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "3+4/2"

That String in the error message is not a valid input to the parseDouble method.
You are going to have to parse that expression to separate the numeric parts from the operators etc and only pass the Strings containing numeric digits to the parse method.
 
Stephan van Hulst
Saloon Keeper
Posts: 7972
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should first tokenize the string. I find you can do this easily with a Scanner that uses a delimiter that can be described as "whitespace or around operators".

After that, you can create a top-down expression parser by converting the following production rules into methods:

Here, the curly braces mean that what's between them can appear once, more than once, or never.

An example of a method signature you could use for one of the production rules.

One possible type of expressions that can be returned from a parse method:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!