Java Reference
In-Depth Information
For example, suppose you create a
Scanner
object as follows:
Scanner keyboard2 =
new
Scanner(System.in);
You can change the delimiter for the object
keyboard2
to
"##"
as follows:
keyboard2.useDelimiter("##");
After this invocation of the
useDelimiter
method,
"##"
will be the only input delim-
iter for the input object
keyboard2
. Note that whitespace will no longer be a delimiter
for keyboard input done with
keyboard2
. For example, suppose the user enters the fol-
lowing keyboard input:
one two##three##
The following code would read the two strings
"one two"
and
"three"
and make
them the values of the variables
word1
and
word2
:
String word1, word2;
word1 = keyboard2.next();
word2 = keyboard2.next();
This is illustrated in Display 2.10. Note that you can have two different objects of the
class
Scanner
with different delimiters in the same program.
Note that no whitespace characters, not even line breaks, serve as an input delimiter
for
keyboard2
once this change is made to
keyboard2
.
Self-Test Exercises
15. Suppose your code creates an object of the class
Scanner
named
keyboard
(as
described in this chapter). Write code to change the delimiter for
keyboard
to a
comma followed by a blank.
16. Continue with the object
keyboard
from Self-Test Exercise 15. Consider the fol-
lowing input:
one,two three, four, five
What values will the following code assign to the variables
word1
and
word2
?
String word1 = keyboard.next();
String word2 = keyboard.next();