2014-10-20 115 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