The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in K&B Book. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Doubt in K&B Book. " Watch "Doubt in K&B Book. " New topic
Author

Doubt in K&B Book.

Pankaj Shet
Ranch Hand

Joined: Sep 08, 2006
Posts: 162

Hi,
This is the question in K&B's book.According to me the answer should be 234 i.e.Option A.
However, in this book the explaination is given as follows.

E is correct.
The \d is looking for digits. The * is a quantifier that looks for 0 to many occurrences of the pattern that precedes it. Because we specified *, the group() method returns empty Strings until consecutive digits are found, so the only time group() returns a value is when it returns 34 when the matcher finds digits starting in position 2. The start() method returns the starting position of the previous match because, again, we said find 0 to many occurrences.
And also A, B, C, D, E, F, and G are incorrect based on the above.
E is included in the incorrect options too.

So there is no way to understand the correct option or the answer.
Given:

import java.util.regex.*;
class Regex2 {
public static void main(String[] args) {
Pattern p = Pattern.compile(args[o]);
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()) {
System.out.print(m.start() + m.group());
}
}
}

And the command line:

java Regex2 "\d*" ab34ef

What is the result?

A.234

B.334

C.2334

D.0123456

E.01234456

F.12334567

G.Compilation fails.


- Thank you.


PANKAJ SHET
B.Sc.(I.T.), S.C.J.P., S.C.W.C.D., PGDAC(CDAC)
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
"According to me the answer should be 234 i.e.Option A."

Nope. Did you run the program with the provided input? If you did, then you would get 01234456 which is the correct answer E. The fact that the text includes E in the list of incorrect answers is a typo error that has been noticed before by several other ranchers.

To understand why the answer is 01234456 check out our FAQ here.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Pankaj Shet
Ranch Hand

Joined: Sep 08, 2006
Posts: 162

sir/madam,
I got the answer. Thanks for reply.
I did'nt run the program before.
Sorry.
-thank you
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Doubt in K&B Book.
 
Similar Threads
Patter and Matcher..Mock Question Doubt
SCJP book regex, pattern and matcher question
K&B Study Guide for Java 5 p498 Selftest problem 1
Regex Doubt
can some one explain me the output of this program?