File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Input error in math equation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Input error in math equation" Watch "Input error in math equation" New topic

Input error in math equation

Greg Gruic

Joined: Apr 30, 2011
Posts: 8
I am creating a program that will calculate a math equation similar to (5+5) + 6*3 + 18. It works when I put spaces between the integers and operators, however if there is no space it gives me a stack error. I know its because I am using s.nextInt(); for numbers and for the operators and if there is no space will pull everything till you get to a space. Any suggestions on how to fix this. Line 57 is my error because of an empty stack. The input is read between 17-24.

Thanks in advance!

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

Did you read the API on the Scanner class?
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
So it needs the (white)space to know where your tokens are.

You may be able to pass it a regex as a pattern, that would have a whitespace or your operators (with an optional space), but I don't know if you can then get the operator...

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: Input error in math equation
It's not a secret anymore!