Java Scanner useDelimiter() Method
Example
Read comma separated items:
// Create a scanner object
Scanner myObj = new Scanner("Item 1,Item 2,Item 3");
// Change delimiter
myObj.useDelimiter(",");
// Read the contents of the scanner
while (myObj.hasNext()) {
System.out.println(myObj.next());
}
Definition and Usage
The useDelimiter()
method changes the delimiter used by the scanner. A delimiter is the sequence of characters which separates tokens in the data being scanned. It is described by a regular expression given by a string or a Pattern
object.
Learn more about regular expressions in our Java RegEx tutorial.
What is a token?
A token is a sequence of characters separated from other tokens by delimiters. The default delimiter is a block of whitespace characters but it can be changed with this method.
Syntax
One of the following:
public Scanner useDelimiter(Pattern pattern)
public Scanner useDelimiter(String pattern)
Parameter Values
Parameter | Description |
---|---|
pattern | Required. A string or Pattern object. A regular expression defining which sequences of characters are considered delimiters. |
Technical Details
Returns: | A reference to the Scanner object that this method belongs to, which allows for chaining configuration methods. An example of chaining is myObj.useDelimiter(",").setRadix(16); . |
---|