Why the 1st block works but the 2nd block doesn't?
int numberOfDigits = 2;
Pattern p = Pattern.compile("[01]{"+numberOfDigits+"}");
Matcher m = p.matcher("101100101011010011111000");
while(m.find()){
System.out.println(m.group());
}
BLock 2
Scanner scannerSegment = new Scanner("101100101011010011111000");
while(scannerSegment.hasNext(p)){
String segment = scannerSegment.next(p);
System.out.println(segment);
}
Scanner
is not the appropriate utility to retrieve patterns using its hasNext(Pattern pattern)
method . It will check if the next complete token has the requested pattern .
Java API is the best document.
Some excerpts:
hasNext() : Returns true if the next complete token matches the specified
pattern. A complete token is prefixed and postfixed by input that matches
the delimiter pattern.`
So if you change the input to be delimited by space or any other delimiter ( other delimiters have to be set after defining the Scanner
object ) , it will work. So this should work(for the current pattern):
Scanner scannerSegment = new Scanner("10 11 00 10 10 11 01 00 11 11 10 00");
Even this will work(for the current pattern):
Scanner scannerSegment = new Scanner("10,11,00,10,10,11,01,00,11,11,10,00");
scannerSegment.useDelimiter(",");
EDIT: Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
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