Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY


462


use the Stringmethods indexOfand substringto extract a string that represents exactly
one floating-point value.

Before we go on, we had better hand-simulate this algorithm. Let’s apply it to the fol-
lowing string:

"23.5 5.6 5.44"

index currentValue line amount
4 “23.5” “5.6 5.44” 23.5
3 “5.6” “5.44” 5.6
error “5.44”

There is an error in the logic. Unless a blank follows the last value rather than an end
of line, the indexOfmethod returns – 1 , indicating that there isn’t another blank. We then
use the indexin the next statement, producing an error in the method substring.We
need to check whether a blank is found. If it is not, the remaining string is the last value
in the line.

We now need to decide what other errors might occur, how to catch them, and how
to handle them. The file can throw an IOException, the conversion operation can throw
a NumberFormatException, and our own code can throw a DataSetException. For the
IOException, let’s catch it, print out the site name, and end the application. For the
NumberFormatException, let’s print out the site name with an error message and continue
processing with the next site. We can do the same for DataSetException.

Get Rainfall Amount (revised)
Set index to line.indexOf(' ')
ifindex > 0
Set currentValue to line.substring(0, index)
Set line to substring(index+1, line.length())
else
Set currentValue to line
Set amount to Double.parseDouble(currentValue)

Get Rainfall Amount
Set index to line.indexOf(' ')
Set currentValue to line.substring(0, index)
Set line to substring(index+1, line.length())
Set amount to Double.parseDouble(currentValue)
Free download pdf