evaluate
Category: Token-Based File Processing
Author: Stuart Reges
Book Chapter: 6.2
Problem: evaluate
Write a static method called evaluate
that takes as a parameter a Scanner containing a series of tokens
that represent a numeric expression involving addition and subtraction and
that returns the value of the expression. For example, if a Scanner called
data contains the following tokens:
4.2 + 3.4 - 4.1
and we make the following call:
evaluate(data)
the method should evaluate the result as (4.2+3.4-4.1) = (7.6-4.1) = 3.5 and
should return this value as its result. Every expression will begin with a
real number and then will have a series of operator/number pairs that
follow. The operators will be either "+" (addition) or "-" (subtraction).
As in the example above, there will be spaces separating numbers and
operators. You may assume the expression is legal.
Your program should evaluate operators sequentially from left to right. For
example, for this expression:
7.3 - 4.1 - 2.0
your method should evaluate the operators as follows:
7.3 - 4.1 - 2.0 = (7.3 - 4.1) - 2.0 = 3.2 - 2.0 = 1.2
The Scanner might contain just a number, in which case your method should
return that number as its result.