This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Scanner findInLine going into infinite loop
 
Similar Threads
Scanner...K&B p.no:484
K & B example Problem.
Searching using Scanner class exp. in K&B SCJP6
Tokenizing
Scanner not scanning for a regular expression