问题
Let me first apologize. I've been coding for a long time now, but I'm new to Java. I feel like this should be a simple error, but I've been working on it for a half hour to no avail:
public String getHtml(HttpServletRequest request) {
try {
WebPageFetcher fetcher = new WebPageFetcher("http://google.com");
} catch (Exception e) {
log.error("WebPageFetcher failed ...");
}
return "<div id=\"header\">" + fetcher.getPageContent() + "</div>";
}
Where WebPageFetcher is implemented as shown here: http://www.javapractices.com/topic/TopicAction.do?Id=147
I'm getting an error:
cannot find symbol
symbol : variable fetcher
location: class myclass
What am I doing wrong?
回答1:
fetcher is visible only in the block where it was declared, the try block. Try declaring before the block so it will be visible throughout the method:
WebPageFetcher fetcher = null;
try {
fetcher = new WebPageFetcher("http://google.com");
}
回答2:
The lifetime of the variable fetcher is only within the most enclosing scope, i.e. the most nested pair of brace ({ }) surrounding it. Therefore, it no longer exists by the time you get to the return statement where you're trying to use it.
回答3:
On the return the variable fetcher is out of scope.
Try:
public String getHtml(HttpServletRequest request) {
try {
WebPageFetcher fetcher = new WebPageFetcher("http://google.com");
// return within scope
return "<div id=\"header\">" + fetcher.getPageContent() + "</div>";
} catch (Exception e) {
log.error("WebPageFetcher failed ...");
}
return /*something that make sense*/ "<html>500</html>";
}
来源:https://stackoverflow.com/questions/4951867/cannot-find-symbol-error