2015-02-08 52 views
0
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"); 
} 

} 
} 

我試圖製作一個程序,它從網站讀取html並將其放入字符串中。然後我想用網站中的html搜索字符串中的單詞。當我執行程序時,我得到錯誤。嘗試搜索字符串內的單詞時出錯(Java)

在wordfinderurl.Wordfinderurl.main(Wordfinderurl.java:19)在線程 「主」 顯示java.lang.NullPointerException 異常

任何幫助理解。

+2

「nullPointerException」幾乎*總是*表示「哎呀!我忘了初始化一些東西!」在你的情況下,查看第19行中使用的變量,並確定哪些變量可能未初始化。提示:如果出於任何原因無法執行http://www.google.com的「openStream()」,會發生什麼情況?提示:當「inputLine」爲空時,你的代碼是做什麼的?提示「也許你應該在你的」while()「行之後加上大括號,也許你應該調用」while「循環中的* inputLine.contains()* *(*之前的* inputLine變爲空)? – FoggyDay 2015-02-08 23:59:43

+0

這是不是一個好主意,可以用行來讀取網頁的輸出,在html中可能沒有換行符,即使它是,你也不想在頁面的任何地方搜索這個單詞,這裏有特殊的HTML解析器一種任務。 – eckes 2015-02-09 02:14:03

回答

0

唯一的例外是在第19行拋出我認爲在這條線:

if(inputLine.contains("new")) ... 

這裏設置inputLinereadLine直到null

while ((inputLine = in.readLine()) != null) 

因此,你得到一個NullPointerException

容易的,但很醜,解決方法可能是(我累了地獄,所以請原諒任何錯誤):

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")){ 

我相信其他人有更好的方法來對待它。