【问题标题】:Object not initialized not sure why对象未初始化不知道为什么
【发布时间】:2017-09-14 20:36:14
【问题描述】:

我正在尝试从文本文件中读取一些内容。 .txt 文件和代码都在我当前的工作目录中。我收到错误 fInput 可能尚未初始化。我相信这是因为我的程序将执行 catch 语句而不是 try。

这是我的代码段:

Scanner fInput;
        try {
            fInput = new Scanner(new File("accountData.txt"));
        }
        catch(Exception e) {
            System.out.println("ERROR: File Not Found.");
        }
        while(fInput.hasNext()) {
            String tempID = fInput.next();
            String tempFName = fInput.next();
            String tempLName = fInput.next();
            String tempPNumber = fInput.next();
            String tempEmail = fInput.next();

            System.out.println(tempID+""+tempFName+""+tempLName+""+tempPNumber+""+tempEmail);
        }

有人能解释一下我为什么会得到这个吗?谢谢。

【问题讨论】:

  • @HovercraftFullOfEels 实际上这不是问题所在。这是由于缺少初始化导致的编译器错误。
  • 是的,我们可以阐明它。不要忽略异常!打印异常并继续,就好像什么都没发生一样,仍然是忽略它。好的,这并不能直接解释您的问题,但修复它也将修复您的编译错误。
  • @HovercraftFullOfEels 感谢您的意见。我已经编辑了 .txt 文件名以包含可执行文件所在的路径,但我得到了同样的错误。
  • @NickM:当你用null声明变量时初始化它。为了我的钱,我会避免将 File 与 Scanner 一起使用,而是使用通过资源获取的 URL。
  • @Andreas 我不一定会忽略这个例外,我只是知道它会因为错误的原因而达到这一点。但我明白你在说什么,我明白这样做是更好的编码实践。我会记住这一点的。

标签: java file exception io


【解决方案1】:

是的,问题是如果在您的try 块中抛出异常,那么fInput 将不会在catch 之后被初始化。因此,编译器无法保证fInput 在到达while 循环时会被初始化。如果您仍然喜欢以这种方式使用Scanner,您可以通过两种方式修复您当前的代码:

  1. 在try 中运行你的循环:

    Scanner fInput;
    try {
        fInput = new Scanner(new File("accountData.txt"));
        while(fInput.hasNext()) {
            String tempID = fInput.next();
            String tempFName = fInput.next();
            String tempLName = fInput.next();
            String tempPNumber = fInput.next();
            String tempEmail = fInput.next();                
            System.out.println(tempID+""+tempFName+""+tempLName+""+tempPNumber+""+tempEmail);
        }
    }
    catch(Exception e) {
        System.out.println("ERROR: File Not Found.");
    }
    
  2. 通过检查确保空值安全:

    Scanner fInput = null; //This change is important!
    try {
        fInput = new Scanner(new File("accountData.txt"));
    }
    catch(Exception e) {
        System.out.println("ERROR: File Not Found.");
    }
    if(fInput!=null) {
        while(fInput.hasNext()) {
            String tempID = fInput.next();
            String tempFName = fInput.next();
            String tempLName = fInput.next();
            String tempPNumber = fInput.next();
            String tempEmail = fInput.next();
            System.out.println(tempID+""+tempFName+""+tempLName+""+tempPNumber+""+tempEmail);
        }
    }
    

这两种方法都可以避免您的示例中可怕的NullPointerException。

【讨论】:

  • 非常感谢。谢谢你的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-28
  • 2020-02-22
  • 1970-01-01
相关资源
最近更新 更多