2014-10-08 41 views
-3

要求:URL解析程序不停止循環

  1. 我需要接受一個字符串作爲參數
  2. 打印出的第一個鏈接就找到
  3. 返回一個整數,是鏈接的指數End或-1如果 找不到鏈接。

如果if語句沒有在字符串中找到「href」,它將返回整數,一個if語句在substring方法將不會獲得索引超出邊界錯誤之前返回-1。

顯示需要返回字符串中的所有http站點。

我相信我是非常密切的,這裏是我的代碼:

public class LinkList { 

public static void main(String[] args) { 
    String htmlCode = (a long string with all my url links) 


    int linkStart = 0; 
    int endLink = 0; 
    while (true) { 
     linkStart = hrefSearch(htmlCode); 
     if(linkStart == -1) break; 
     htmlCode = htmlCode.substring(linkStart); 
    } 

} 

public static int hrefSearch (String inStr) { 

    String find = " href="; 
    String closingBracket = ">"; 


    int index = inStr.indexOf(find); 

    if (index != -1){ 
     int closing = inStr.indexOf(closingBracket, index); 

    if (closing != -1){ 
     System.out.println(inStr.substring (index, closing + 1)); 

     } 
} 
    return index; 
}} 

我怎樣才能得到我的程序停止循環,並顯示在我的字符串的所有網址?

+3

您應該先閱讀幫助中心。你的問題主體和標題有很多噪音,但沒有真正的問題。 – 2014-10-08 05:06:22

+0

你的代碼產生了什麼輸出?什麼不行? – Eran 2014-10-08 05:08:03

+0

不會''href =「'更合適嗎? – MadProgrammer 2014-10-08 05:08:08

回答

0

變化:

htmlCode = htmlCode.substring(linkStart); 

到:

htmlCode = htmlCode.substring(linkStart+1); 

否則,你會繼續一遍又一遍找到第一個URL(因爲linkStart就是以前的URL開始的位置,所以htmlCode.substring(linkStart)仍然包含您找到的以前的網址)。

+0

我一直在敲着我的頭對着鍵盤的東西那麼小。 – 2014-10-08 05:21:04

+0

@jc不客氣! – Eran 2014-10-08 05:22:10

+0

我將在另一個程序中發佈另一個問題。你能幫我解決嗎? – 2014-10-08 05:23:59