2013-02-12 42 views
3

我在讀取txt文件時遇到問題,並使用java的scanner.util查找單詞/模式。 目前正在測試閱讀,我收到每行的盈方。在這個問題之後,我仍然不確定如何搜索txt文件中的模式/單詞。我還必須顯示包含模式/單詞的行。掃描txt文件時在每行之前爲空

public class SearchPattern { 
    public static void main(String[] args) throws IOException{ 
     Scanner s = new Scanner(System.in); 
     String pattern; 
     String filename; 
     String[] text = new String[10]; 
     System.out.println("Enter the filename"); 
     filename = s.nextLine(); 
     System.out.println("Enter the pattern you'd like to search"); 
     pattern = s.nextLine(); 
     // Print out each line that contains pattern 
     // may need an array to store StringS of lines with word 
     try{ 
     s = new Scanner(new BufferedReader(new FileReader(filename))); 
     int x = 0; 
     while (s.hasNext()) { 
      text[x] += s.next(); 
      x++; 
     } 
     } 
     finally { 
     if (s != null) { 
      s.close(); 
     } 
     } 
     text[0] = "test"; 
     System.out.println(text[0]); 
     for(String txt : text){ 
     System.out.println(txt); 
     } 
    } 
} 

回答

2
s = new Scanner(new BufferedReader(new FileReader(filename))); 
     int x = 0; 
     while (s.hasNext()) { 
      text[x] += s.next(); 
      x++; 
     } 

你在這裏做什麼,正在迭代你的陣列,我猜你不會這麼做。

現在,爲你的陣列中的每個x位置,你寫

text[x] = text[x] + s.next(); 

但你可能想要做的就是給你的陣列中的每個位置上的掃描器的下一個值的值。在代碼

text[x] = s.next(); 

這也可以寫成

 for((int x = 0; s.hasNext(); x++) 
      text[x] = s.next(); 

希望這有助於。祝你好運!

3

你這樣做:

text[x] += s.next(); 

這意味着:text[x]null比你追加s.next()

將其替換爲:

text[x] = s.next(); 
+0

你先回答並解決了我的問題,但其他人回答得更詳細,這有助於我進一步理解。非常感謝您的支持,並非常抱歉,您會因爲這樣的noob問題而煩惱您。 – 2013-02-13 05:19:17

相關問題