2017-04-18 66 views
-3

我试图从文本文件中读取一些东西。 .txt文件和和代码都在我目前的工作目录中。我得到的错误fInput可能尚未初始化。我相信这是因为我的计划是按照我的抓住声明而不是尝试。对象未初始化不知道为什么

这里是我的代码段:

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); 
     } 

有谁能够解释为什么我得到这个一些启示?谢谢。

+2

@HovercraftFullOfEels其实这不是问题在这里。这是由于缺少初始化而导致的编译器错误。 – Zircon

+0

是的,我们可以阐明它。不要忽略例外!打印异常并继续,如果没有发生,仍然*忽略*它。好的,这并不直接解释你的问题,但修复它也会解决你的编译错误。 – Andreas

+0

@HovercraftFullOfEels感谢您的输入。我编辑了.txt文件名以包含可执行文件所在的路径,并且出现相同的错误。 –

回答

0

是的,问题是,如果在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在你的例子中。

+0

非常感谢。感谢您的解释。 –