Java Reference
In-Depth Information
Display 2.10
Changing the Input Delimiter
1
import
java.util.Scanner;
2
public class
DelimiterDemo
3{
4
public static void
main(String[] args)
5
{
6
Scanner keyboard1 =
new
Scanner(System.in);
7
Scanner keyboard2 =
new
Scanner(System.in);
8
keyboard2.useDelimiter("##");
9
//Delimiter for keyboard1 is whitespace.
10
//Delimiter for keyboard2 is ##.
11
String word1, word2;
12
System.out.println("Enter a line of text:");
13
word1 = keyboard1.next();
14
word2 = keyboard1.next();
15
System.out.println("For keyboard1 the two words read are:");
16
System.out.println(word1);
17
System.out.println(word2);
18
String junk = keyboard1.nextLine();
//To get rid of rest of line.
19
20 System.out.println("Reenter the same line of text:");
21 word1 = keyboard2.next();
22 word2 = keyboard2.next();
23 System.out.println("For keyboard2 the two words read are:");
24 System.out.println(word1);
25 System.out.println(word2);
26 }
27 }
Sample Dialogue
Enter a line of text:
one two##three##
For keyboard1 the two words read are:
one
two##three##
Reenter the same line of text:
one two##three##
For keyboard2 the two words read are:
one two
three