2016-03-04 20 views
0

我在分配時遇到了一些問題。我相信我已經有了覆蓋搜索方法的基礎,但是在我的代碼中有一個錯誤導致它無法工作。您必須通過掃描器方法輸入文件,並且只允許通過charAt()和length搜索字符串,但不允許在字符串或字符串構建器類中使用其他方法。僅使用charAt()和length()的Java搜索文本文件()

我必須在文件中搜索該單詞並報告找到該單詞的次數以及它所在的行號。

任何幫助表示讚賞,感謝。

public void FindWord(String fileName, String word)throws IOException 
{ 
    Scanner fileInput = new Scanner (new File(fileName));//scanner that reads the file 
    int lineCounter = 0; //declares the line 
    String line; 

    while (fileInput.hasNextLine()) 
    { 
     line = fileInput.nextLine(); 
     System.out.println(line); 
     lineCounter++; 
     outerloop: for (int i = 0; i <= line.length();i++) 
     { 
      for (int j = 0; j <= word.length();) 
      { 
       if (line.charAt(i) == word.charAt(j)) 
       { 
        if (j == word.length()) 
        { 
         amount++; 
         lineNumbers += (lineCounter + ", "); 
         continue outerloop; 
        } 
        j++; 
        i++; 
       } 

       else if (line.charAt(j) != word.charAt(j)) 
       { 
        continue outerloop; 
       } 

      } 
     } 
    } 
} 

編輯:嗯,我確實縮小了它的具體問題。代碼運行直到if語句中,我檢查由輸入文件創建的名爲「line」的字符串與輸入的名爲string的字符串。它會產生一個超出界限的錯誤,數字爲4,但這會讓我感到困惑,因爲在名爲line的字符串中肯定存在超過4個字符。我可以改變if語句來產生沒有這個錯誤的真實結果,但是我的所有變量都沒有增加它們的值並保持爲0,這仍然證明我的if語句不起作用。

所以基本上,我需要幫助找到解決在對陣字輸入線檢查字符,只使用的charAt()和長度()方法

+0

它可以幫助我們,如果你寫什麼ypur代碼錯誤 - 輸入,期望的輸出和你的輸出/錯誤的例子。 – TDG

+0

是的,請提供您的錯誤日誌 –

+1

歡迎來到StackOverflow。形式問題「這是我的代碼,請找到我的問題」被認爲是題外話。你甚至沒有描述過問題所在。您應該將問題的範圍縮小到一個特定的問題,主要是通過逐步查看代碼來確定行爲與您的期望不符。一個好的問題陳述的例子是:「當我開始排隊時,一些java代碼變量x的值爲y,但我期望的是z的值_」請訪問[help]並閱讀[ask ]。 –

回答

-1

我希望,這個代碼將解決您的問題。請檢查。

import java.io.File; 
import java.io.IOException; 
import java.util.Scanner; 

public class Program { 

    public static void main(String[] args) throws IOException { 
     String fileName = "F:/input.txt"; 
     String word = "name"; 
     FindWord(fileName, word); 
    } 
    public static void FindWord(String fileName, String word)throws IOException 
    { 
     Scanner fileInput = new Scanner (new File(fileName));//scanner that reads the file 
     int lineCounter = 0; //declares the line 
     String line; 

     while (fileInput.hasNextLine()) 
     { 
      int amount = 0; 
      String lineNumbers = ""; 
      line = fileInput.nextLine(); 
      System.out.println(line); 
      lineCounter++; 
      outerloop: for (int i = 0; i <= line.length();i++) 
      { 
       for (int j = 0; j <= word.length();) 
       { 
        if (line.charAt(i) == word.charAt(j)) 
        { 
         if (j == word.length()) 
         { 
          amount++; 
          lineNumbers += (lineCounter + ", "); 
          continue outerloop; 
         } 
         j++; 
         i++; 
        } 

        else if (line.charAt(j) != word.charAt(j)) 
        { 
         continue outerloop; 
        } 

       } 
      } 
     } 
    } 
} 
+0

對不起SkyWalker,這並不能解決我的問題。 – gskiii52