Cannot find symbol error [duplicate]

非 Y 不嫁゛ 提交于 2019-12-11 03:29:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!