程序不扫描文本文件(Java)

时间:2014-10-20 00:55:12

标签: java text

我无法让我的程序从文件中读取" lexicon.txt" 我的任务是让程序扫描用户输入并获得程序的字数作为回报。你们知道我的代码中发生了什么吗?

import java.io.*;
import java.util.Scanner; 
public class searchFile {
public static void main (String args[]) throws IOException {
    Scanner reader = new Scanner(System.in);
    System.out.println("Please enter the file name (e.g: nonamefile.txt)");
    String objective = reader.nextLine();

    if (!(objective.equals("lexicon.txt"))) {
        System.out.println("ERROR: Missing File");
    }
    else {
        Scanner reader2 = new Scanner(System.in);
        Scanner lexicon = new Scanner(new File("lexicon.txt"));
        int wordCount = 0;
        System.out.println("What word do you need to look up?");
        String objective2 = reader2.nextLine();

        while (lexicon.hasNext()) {
            String word = lexicon.next();
            if (word.equalsIgnoreCase(objective2)){
                wordCount++;
            }                
        }
        System.out.println("Word count = " + wordCount);
    }
} // end main method (String Args[])
} // end class searchFile

1 个答案:

答案 0 :(得分:0)

我在电脑上运行了你的代码。它是为了帮助你。可能你没有这样做。

Please enter the file name (e.g: nonamefile.txt)
lexicon.txt
What word do you need to look up?
three
Word count = 3

我在lexicon.txt中使用的文字是:

one
two two 
three three three

它工作正常。
请记住,只是复制粘贴不像你想象的那样。复制时无法看到剪贴板中的任何字符,粘贴它也会在文本文件中粘贴这些代码。 Scanner.next()查找由word boundries分隔的下一个字符串 假设您复制粘贴的文本:
enter image description here
这在记事本中不可见:
enter image description here
因此,当您搜索" Hello"时,它将不在那里 您将不得不搜索enter image description here,但不能轻易地写出来。

相关问题