• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scanner question or maybe it may be more about java class API's

 
Quintin Stephenson
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers

I've been reading the Scanner class API web page found on Sun's web site(http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html).

It includes the following code snippet:

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i);
s.close();

What has confused me is that is the method summary on the same page, it states that findInLine returns a String value. The above example clearly does not return a value into a String. My question is as follows:

Is it the case that because it returns a value that is sub-classed off Object that it imlicitly performs a "new String()" and creates an anonamous instance of the object (in this case a String)? Or is there something else happening here?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What has confused me is that is the method summary on the same page, it states that findInLine returns a String value. The above example clearly does not return a value into a String.


The findInLine() method you are referring to does return a String, the return value is just ignored in this case. You could choose not to ignore it however:


Although in this case the entire input String would be returned.
 
jan ter avest
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I asked this question yesterday!

http://www.coderanch.com/t/261497/java-programmer-SCJP/certification/Scanner-MatchResult

Anyway, the result of method s.findInLine() may be ignored but somehow its pattern is used in s.match().

How do you explain that?
[ February 12, 2007: Message edited by: jan ter avest ]
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from the Javadocs for Scanner.java.

match

public MatchResult match()

Returns the match result of the last scanning operation performed by this scanner. This method throws IllegalStateException if no match has been performed, or if the last match was not successful.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic