• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Scanner findInLine going into infinite loop

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank You
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic