According to Java API Scanner uses delimiters to break the whole input into tokens. I am trying to understand the tokens and delimiters. I was doing this program and hit a confusion
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner s = null;
try {
s = new Scanner(System.in);
s.useDelimiter("A");
System.out.println("1 " + s.next().length());
System.out.println("2 " + s.next().length());
System.out.println("3 " + s.next().length());
System.out.println("4 " + s.next().length());
} finally {
if (s != null) {
s.close();
}
}
}
}
When I use the input AAAAAasdf
I get the following output.
1 0
2 0
3 0
4 0
I can understand this output as the length of tokens is zero between the delimiters hence all are zero but when I use the default delimiters and give the input as
_____aaa\n
->Replace underscore by space and \n
by me hitting enter in eclipse console.
For this I am getting the output as
1 3
which I cannot understand. I have given 5 spaces so there should be 4 tokens of 0 lengths between them. Why not? What am I missing here?
The delimiter() is a method of Java Scanner class which is used to get the Pattern which the Scanner class is currently using to match delimiters.
The useDelimiter(String pattern) method of java. util. Scanner class Sets this scanner's delimiting pattern to a pattern constructed from the specified String. Parameter: The function accepts a mandatory parameter string pattern which specifies a delimiting pattern.
Scanner delimiter() method in Java with Examples Return Value: The function returns the scanner's delimiting pattern. Scanner scanner = new Scanner(s); // Set the delimiter to "."
A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. Leading whitespace before a valid delimiter is silently ignored. Often used delimiters are forward slashes ( / ), hash signs ( # ) and tildes ( ~ ). The following are all examples of valid delimited patterns.
useDelimiter takes a regular expression pattern. The default pattern is
private static Pattern WHITESPACE_PATTERN = Pattern.compile(
"\\p{javaWhitespace}+");
Which will match any amount of contiguous whitespace. If you want the delimiter to match any amount of contiguous A try something like
s.useDelimiter("[A]+");
Read these: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String) http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#reset()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With