Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scanner findInLine going into infinite loop

 
Ganesha Kumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic