[英]My java program seems to be skipping over the try{}, executing the catch{} and then throwing a NullPointerException. What should I do?
我正在编写一个程序,用于计算任何给定文本文件中的单词,音节和句子的数量。 我不需要帮助查找这些数字,但是我的程序(当前应该只找到文本文件中的单词数)将不会导入文本文件,即使我正确输入文件的名称。 文本文件与源代码位于同一文件夹中。 相反,它告诉我每次输入的内容都有错误的文件扩展名(请参阅我的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);
}
}
你的catch设置scan = null
,然后在下一行(catch之外)使用scan.hasNext()
- 如果你经历了catch你知道scan是null,所以这会给你一个NullPointerException。
您可能应该抛出异常或使代码足够健壮以应对空扫描器(即不执行任何操作)
尝试这个...
try{
scan = new Scanner(doc);
}catch(Exception e){
e.printStackTrace();
}
看看Scanner
初始化的问题是什么。
如果从命令行运行,请将目录更改为源文件所在的文件夹。 (我假设类文件和txt文件也在同一个目录中)
如果源文件在c:\\ src中
C:
cd c:\\ src
java Reading_Lvl_Calc
用等号()替换运算符进行比较:
if(fileName.substring(fileName.indexOf(".")) != ".txt")
to
if((fileName.substring(fileName.indexOf("."))).equals(".txt"))
在上述条件下,我们可以验证扫描obj是否为空,然后迭代扫描对象.....
if(scan != null){
while(scan.hasNext()){
words++;
scan.next();
}
}
在对象(例如字符串)上使用'=='和'!='运算符通常是一个坏主意,因为对象变量的实际值是内存地址,因此对象通过引用进行比较,在您的情况下不是期望的效果:你不关心fileName.substring(fileName.indexOf(“。”))和“.txt”在内存中共享相同的位置(他们不会)。 使用.equals()代替按值进行比较。 否则,测试将始终返回false,并且if语句无用。
我同意ValekHalfHart在这里告诉你,我检查了下面的代码,我认为它将处理“有无效的文件扩展名”问题。
改变
if(fileName.substring(fileName.indexOf(".")) != ".txt")
至
if(!fileName.substring(fileName.indexOf(".").equals(".txt"))
这应该做到这一点
当扫描程序创建失败时,没有任何必要做任何与扫描程序相关的事情,因此您应将所有扫描程序代码放入try块中,并将一些错误消息放入catch块中。 在继续创建扫描仪之前,应先检查文件名。
try
{
scan = new Scanner(doc);
while(scan.hasNext())
{
words++;
scan.next();
}
System.out.println(words);
}
catch(Exception e)
{
System.out.println("Scanner creation failure:" + e.getMessage());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.