jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Scanner findInLine going into infinite loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Scanner findInLine going into infinite loop" Watch "Scanner findInLine going into infinite loop" New topic
Author

Scanner findInLine going into infinite loop

Ganesha Kumar
Ranch Hand

Joined: May 04, 2006
Posts: 56
Hi,
I have found that the following code goes into infinite loop when I use space in the String argument for the Scanner constructor.


import java.util.*;

public class UseScannerAgain{
public static void main(String args[]){
try{
Scanner s = new Scanner("12 22 1221");
String token = null;
do{
token = s.findInLine("\\d*");
System.out.println("token "+token);
}while(token !=null);
}
catch(Exception e){
e.printStackTrace();
}
}
}


Can anyone tell me the reason for this.
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Ganesh,


This infinite loop is because of "\\d*", greedy quantifier. "*" asterisk is greedy for 0 or more. It goes on on on and on and finds blank string and blank is not == null so your loop continues.

Try this modified code:


Try to compile replacing Line #1 by :

token = s.findInLine("\\d*"); // with greedy *

you will see a lot of >< ; that is what blank String is found and loop continues because blank string "" != null.


Note: [You may use "\\d+" instead; that says one or more]

Thanks,
[ May 05, 2007: Message edited by: Chandra Bhatt ]

cmbhatt
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Anyway to solve your purpose specifically you can try this code:




Output:
12
22
1221

And yeah, if you want to get the positions of the found results, go with Pattern and Matcher classes because Scanner class lacks this facility.
Ganesha Kumar
Ranch Hand

Joined: May 04, 2006
Posts: 56
Thank You
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Scanner findInLine going into infinite loop