Home Segments Index Top Previous Next

464: Sidetrip

You cannot use the nextWord message to read floating-point numbers, because nextWord stops reading when it encounters a decimal point. Fortunately, you can define nextNumber, which reads numbers whether they are Integer instances or Float instances.

The following simple version of the nextNumber method uses peek to determine whether the first part of the number is followed by a decimal point; if so, it reads the rest, and uses asFloat to convert the concatenated parts:

Stream method definition • instance 
nextNumber 
  | number fraction | 
  number := self nextWord. 
  self peek = $. 
    ifTrue: [fraction := self nextWord. 
             ^ (number , '.' , fraction) asFloat] 
    ifFalse: [^ number asInteger]