我正在编写一个程序来计算任何给定文本文件中的单词、音节和句子的数量。我不需要帮助来查找这些数字,但是即使我正确输入了文件名,我的程序(目前只能查找文本文件中的字数)也不会导入文本文件。文本文件与源代码位于同一文件夹中。相反,它每次都告诉我我输入的文件扩展名错误(请参阅我的 catch{}),然后继续抛出一个空指针。我不知道是什么原因造成的。有什么建议么?
import java.io.*;
import java.util.*;
public class Reading_Lvl_Calc {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int words = 0;
String fileName;
Scanner scan;
Scanner keyread = new Scanner(System.in);
System.out.println("Please enter a file name (or QUIT to exit)");
fileName = keyread.nextLine();
File doc = new File(fileName);
//while(scan.equals(null)){
try
{
scan = new Scanner(doc);
}
catch(Exception e)
{
if(fileName.substring(fileName.indexOf(".")) != ".txt")
System.out.println("I'm sorry, the file \"" + fileName + "\" has an invalid file extension.");
else
System.out.println("I am sorry, the file \"" + fileName + " \" cannot be found.\n The file must be in the same directory as this program");
scan = null;
}
// }
while(scan.hasNext()){
words++;
scan.next();
}
System.out.println(words);
}
}