2014-09-22 103 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