This is the error message I get.
-DEBUG: The String calculation has just been created.
-DEBUG: The Scanner has just been created.
-DEBUG: The boolean calculateFinished has just been created.
-DEBUG: The input has just been recorded.
Exception in thread "main" java.lang.NumberFormatException: For input string: "12+6"
Alix Ollivier wrote:I am working on a project to create a calculator...However, I don't know how to parse it properly...
Hmmm. Can I suggest that this might be the basic problem?
And if that sounds obvious, then why are you writing code?
You cannot solve a problem by coding; you can only solve it by thinking...and reading...and scribbling...and thinking some more.
And only when you've done all that and know what you want to do, then you open your Java editor...
Believe me, things will become an awful lot simpler when you get into that habit.
However, just to set you on your way:
1. If this expression involves exactly TWO numbers and an operator in between, then forget the rest of this list.
2. The way we puny humans write mathematical expression is called "infix" notation and computers hate it, because it's horribly illogical.
3. The way computers like to deal with mathematical expressions is with something called Reverse Polish Notation (RPN).
4. A very clever Dutchman called Edsker Dijkstra invented the Shunting yard algorithm to deal with this precise problem: converting puny human expressions to RPN.
If you're only interested in point 1, then you need to look at String.split() and see how you might break up your simple expression.
If you're interested in general parsing of infix expressions (points 2-4), I suspect you're not quite ready for #4; and that's unfortunately where it ends (for the moment; but hopefully only for the moment). If you want to prove me wrong, by all means have a crack at it, and I'll try and help you if you do. But it seems a bit of a stretch at the moment to me.
This may be throwing a monkey wrench in the debate, as I agree with Winston's previous post... however....
Ulf Dittmer wrote:Java has no built-in facilities for this. You can use a parser like this one that I wrote some time ago, or use a library like JEP or JEL.
Nope, absolutely no monkey wrench; just good sense.
@Alix: Henry's post brings up a very good point (which I completely forgot about): Don't re-invent the wheel.
It has to be said that using a scripting engine is likely to be a lot slower than a pure Java-based solution, but hey, if it's fast enough, that's all you need.