Java Reference
In-Depth Information
fgh
int = 123
ijk
The following example demonstrates using a delimiter that is a regular expression by
invoking the useDelimiter method. Study the code and see if you can determine its output:
String status = “probable,questionable;doubtful:out”;
Scanner in = new Scanner(status);
in.useDelimiter(“[,;:]”);
while(in.hasNext()) {
String token = in.next();
System.out.println(token);
}
The delimiter pattern [,;:] is any character that is a comma, semicolon, or colon.
Therefore, the output of the code is
probable
questionable
doubtful
out
Using Scanner for Keyboard Input
A common use of the Scanner class is for keyboard input. Use System.in as the source
of the text and the “next” methods wait for the user to input data. The following example
reads in three tokens from the console separated by whitespace:
25. Scanner console = new Scanner(System.in);
26. System.out.print(“Enter a String, int and double: “);
27. String first = console.next();
28. int middle = console.nextInt();
29. double last = console.nextDouble();
30. System.out.println(“first = “ + first);
31. System.out.println(“middle = “ + middle);
32. System.out.println(“last = “ + last);
Whitespace includes spaces and line feeds so that the user can input the tokens on a
single line separated by spaces. A sample execution of the code is
Enter a String, int and double: first 123 4.567
first = first
middle = 123
last = 4.567
Search WWH ::




Custom Search