Example from text, pg. 399, changed a little
Scanner input = new Scanner(“18.4 17.9 11 20”); //Scanner constructor call
double x = input.nextDouble(); //scans “18.4 “ and puts 18.4 in x;
double y = input.nextDouble(); //scans “17.9 “ and puts 17.9 in y;
input.useRadix(16); // changes scanner to a hex scanner
int x = input.nextInt(); // scans “11 “, puts 17 in x (one 16 plus one 1)
or the whole loop shown on pg. 399:
Scanner input = new Scanner(“18.4 17.9 11 20”);
while (input.hasNextDouble()) {
double next = input.nextDouble();
System.out.println(next);
}
which prints:
18.4
17.9
11.0
20.0
Note: also need import java.util.*; at top of program
We can imagine what’s in the Scanner object, its “object state”, or ”fields”
· The source String
· A value of the current position in the string
·
The current radix
Just after construction: reference “input” pointing to Scanner object:
|
|
After first input.hasNextDouble() call in the loop: same as above, no change
After first input.nextDouble() call: internal position changes to 5, just at the space that delimited the first number:
|
ßactually position = 4, at the space after 18.4
After second input.nextDouble() call: internal position changes to 10, just at the space that delimited the second number:
|
ßactually position = 9, at the space after 17.9
After input.useRadix() call: internal radix changes to 16:
|
ßactually position = 9, at the space after 17.9
After input.nextInt() call: position steps past “11 “, nextInt returns int 17, the hex value of “11”.
|
ßactually position = 12, at the space after 11