2014-10-20 116 views
0

我在使程序从文件“lexicon.txt”中读取时遇到问题 我的任务是让程序扫描用户输入并获取程序的字数作为回报。你们知道我的代码中发生了什么吗?程序不扫描文本文件(Java)

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 
+0

尝试添加'System.out.println(新文件(“lexicon.txt”)。exists());'并确保它打印出'true' ... – MadProgrammer 2014-10-20 00:56:14

+1

没有看到文件,很难知道,但也许'String word = lexicon.nextLine();'会更有用...也许不是... – MadProgrammer 2014-10-20 00:56:57

+0

是的,它打印真正的...和nextLine()方法不会改变任何东西。 – Destinox 2014-10-20 00:57:08

回答

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
所以,当你搜索“你好”,它不会在那里。
您将不得不搜索enter image description here,但不能轻松写出。

+0

哇,它的工作原理!那么复制和粘贴代码与我们实际键入的词有什么区别? – Destinox 2014-10-20 01:25:44

+0

我明白了。需要检查文本内容。非常感谢! – Destinox 2014-10-20 01:57:04