Java Reference
In-Depth Information
Other Input Delimiters
When using the
Scanner
class for keyboard input, you can change the delimiters that
separate keyboard input to almost any combination of characters, but the details are a bit
involved. In this topic, we will describe only one simple kind of delimiter change. We will
tell you how to change the delimiters from whitespace to one specific delimiter string.
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
delimiter 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 following 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
16. 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.
17.
Continue with the object
keyboard
from Self-Test Exercise 16. Consider the
following 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();