我在使程序從文件「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
嘗試添加'System.out.println(新文件(「lexicon.txt」)。exists());'並確保它打印出'true' ... – MadProgrammer 2014-10-20 00:56:14
沒有看到文件,很難知道,但也許'String word = lexicon.nextLine();'會更有用...也許不是... – MadProgrammer 2014-10-20 00:56:57
是的,它打印真正的...和nextLine()方法不會改變任何東西。 – Destinox 2014-10-20 00:57:08