2014-09-22 104 views
0

我有一些問題。我有一個* txt文件,我正在閱讀該程序(PART A)。這很好,使用掃描儀搜索B部分中的單詞/名稱「Winnie-the-Pooh」也是如此。我遇到的問題是C部分,我希望用戶爲他/她自己用哪個詞搜索* txt文件。用戶自定義搜索,通過txt文件搜索

看來無論我在做什麼,掃描儀返回4(文本中最後一個單詞出現的次數)。

希望有你們的可以幫助我與C部分

下面是代碼,並將其編譯就好了。

謝謝。

import java.util.Scanner; 
import java.io.File; 
import java.io.BufferedReader; 
import java.io.FileReader; 

public class Innlesing { 
    public static void main(String[] args) throws Exception { 

    String winnie; 
    int antall = 0; 
    int linjeNummer = 1; 
    String filNavn = "winnie.txt"; 
    Scanner scanFil = new Scanner(new File(filNavn)); 

    // PART A 
    while (scanFil.hasNextLine()) { 
     String linje = scanFil.nextLine(); 
     System.out.println("Linje " + linjeNummer + ": " + linje); 
     linjeNummer++; 
    } 

    // PART B 
    Scanner soekeOrd = new Scanner(new File(filNavn)); 
    while (soekeOrd.hasNextLine()){ 
     winnie = soekeOrd.nextLine(); 
     if (winnie.equals("Winnie-the-Pooh")){ 
     antall += 1; 
     } 
    } 

    System.out.println("Antall forekomster av Winnie-the-Pooh er: " + antall); 

    // PART C 
    Scanner brukerInput = new Scanner(System.in); 
    String brukerInput2; 

    System.out.println("Hvilket ord vil du soeke paa?: "); 
    brukerInput2 = brukerInput.nextLine(); 

    while (scanFil.hasNextLine()) { 
     brukerInput2 = scanFil.nextLine(); 
     if (brukerInput.equals("pluskvamperfektum")) { 
     antall +=1; 
     } 
    } 
System.out.println("Antall forekomster av " + brukerInput2 + " er: " + antall); 
    } 
} 

回答

0

您的代碼有幾個錯誤。 C部分已更正。首先,使用brukerInput.equals(「pluskvamperfektum」)來檢查Scanner實例是否等於String文字。您需要從文件中讀取一行,並檢查用戶輸入的字符串是否爲其中的一部分 - 例如,它發生在非負數索引中。你也忘了重置計數器。在現實生活中,更重要的一點是在不需要時關閉所有資源 - 這一次我已經做到了soekeOrd2。

antall = 0; 
Scanner soekeOrd2 = new Scanner(new File(filNavn)); 
Scanner brukerInput = new Scanner(System.in); 
String brukerInput2; 

System.out.println("Hvilket ord vil du soeke paa?: "); 
brukerInput2 = brukerInput.nextLine(); 

while (soekeOrd2.hasNextLine()) { 
    String line = soekeOrd2.nextLine(); 
    if (line.indexOf(brukerInput2) >= 0) { 
    antall +=1; 
    } 
} 
System.out.println("Antall forekomster av " + brukerInput2 + " er: " + antall); 
soekeOrd2.close() 

問候:巴拉茲

+0

感謝一大堆!你的回答非常有幫助,併爲我解決了一些嚴重的問題。我希望我可以將您的答案投票,但我沒有足夠的代表。 – kimbert007 2014-09-23 17:36:11