程序不扫描文本文件(Java)
问题描述:
我在使程序从文件“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
答
我在计算机上运行了您的代码。这是为了帮助你。可能你是不一样的。
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
分隔的下一个字符串。
假设有你复制粘贴文本:
这是不是在记事本中可见:
所以,当你搜索“你好”,它不会在那里。
您将不得不搜索,但不能轻松写出。
尝试添加'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