problem calling a java function twice? Only first works.

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

problem calling a java function twice? Only first works.

Postby cyberpine » Tue Sep 07, 2010 1:01 am

I've got this function that extracts strings from Inputstreams and returns a List<string>. It uses java.util.Scanner and java.util.regex.Pattern.

Problem is, it only seems to work the first time I call it. If I reverse my calls, again only the first one works, the second call never returns any matches.

List<String> lsphones = extract(is,pattern,0);
List<String> lsemails = extract(is,pattern",0);


I suspect I need to reset the Lists or something in the funciton -if not the function itself somehow. I've tried but keep getting exceptions when I do.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public static List<String> extract(InputStream in,String matchpattern,int grp) {  
  2. ..
  3. scanner.close();
  4. return what
Parsed in 0.029 seconds, using GeSHi 1.0.8.4



Thanks for any help.
cyberpine
Junior Developer
Junior Developer
 
Posts: 10
Joined: Mon Sep 06, 2010 1:56 pm

Top

Re: problem calling a java function twice? Only first works.

Postby smr » Tue Sep 07, 2010 6:53 pm

I suspect it has something to do with scanner.close(), but I don't know for sure because you don't show where you initialize it. Is scanner a static field? When do you call scanner.open() or whatever the opposite of your scanner.close() invocation is?
smr
Freshman
Freshman
 
Posts: 3
Joined: Fri Feb 26, 2010 8:17 pm
Location: Pekin, Illinois

Re: problem calling a java function twice? Only first works.

Postby cyberpine » Tue Sep 07, 2010 9:38 pm

I added scanner.close to try and fix the issue. I've since taken it out. I got around this issue by scanning only once and complicating my regex. It's faster now, but do wonder what the issue was .

Thanks.

public static List<String> extract(InputStream in,String matchpattern,int grp) {
Pattern extractPattern = Pattern.compile(matchpattern);
System.out.println("########################### pattern : "+matchpattern);
List<String> what = new ArrayList<String>();
Scanner scanner = new Scanner(in, "UTF-8");
String match = "";
while (match != null) {
match = scanner.findWithinHorizon(extractPattern, 0);
if (match != null) {
String matchit = scanner.match().group(grp);
System.out.println("########################### match : "+matchit);
what.add(matchit);
}
}
return what;
cyberpine
Junior Developer
Junior Developer
 
Posts: 10
Joined: Mon Sep 06, 2010 1:56 pm

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 3 guests