尝试搜索字符串中的单词时出错(Java)

尝试搜索字符串中的单词时出错(Java),java,nullpointerexception,Java,Nullpointerexception,我正在尝试制作一个程序,从网站读取html并将其放入字符串中。然后我想从网站上用html搜索字符串中的单词。当我执行程序时,我得到了错误 线程“main”java.lang.NullPointerException中出现异常 位于wordfinderurl.wordfinderurl.main(wordfinderurl.java:19) 非常感谢您的帮助。第19行将抛出异常。我假设这是一条线: package wordfinderurl; import java.io.BufferedRead

我正在尝试制作一个程序,从网站读取html并将其放入字符串中。然后我想从网站上用html搜索字符串中的单词。当我执行程序时,我得到了错误

线程“main”java.lang.NullPointerException中出现异常 位于wordfinderurl.wordfinderurl.main(wordfinderurl.java:19)


非常感谢您的帮助。

第19行将抛出异常。我假设这是一条线:

package wordfinderurl;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.swing.JOptionPane;
public class Wordfinderurl {
    public static void main(String[] args) throws Exception {
        // connect to website and output html to a string
   URL leagueoflegends = new URL("http://www.google.com");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(leagueoflegends.openStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
    // search the word "new" in the String inputLine 
    if(inputLine.contains("new")){
    JOptionPane.showMessageDialog(null, "word found");
   }else{
   JOptionPane.showMessageDialog(null, "word not found");
}

}
}
在这里,您可以将
inputLine
设置为
readLine
,直到它为
null

    if(inputLine.contains("new")) ...
因此,您会得到一个
NullPointerException

简单但丑陋的解决方法可能是(我累得要命,所以请原谅我的错误):


我相信其他人有更好的方法来处理它。

“nullPointerException”几乎总是意味着“哇!我忘了初始化某些东西!”在您的例子中,请查看第19行中使用的变量,找出其中哪些可能未初始化。提示:无论出于何种原因,如果您不能执行的“openStream()”,会发生什么?提示:当“inputLine”为空时,您的代码做什么?提示“也许您应该在“while()”行后面加大括号,也许您应该在“while”循环内部调用
inputLine.contains()
(inputLine变为null之前)?逐行阅读网页的输出不是一个好主意。html中可能没有换行符,即使是这样,你也不想在网页的任何地方搜索单词。有专门的html解析器用于此类任务。
    while ((inputLine = in.readLine()) != null)
String inputLine;
String tmp;
while ((tmp = in.readLine()) != null)
    inputLine = tmp;
    System.out.println(inputLine);
in.close();
// search the word "new" in the String inputLine 
if(inputLine.contains("new")){