2014-11-22 88 views
0

我收到错误,说明变量fin可能没有在下面的程序中初始化。请澄清有关初始化的概念。 :什么时候需要在java中初始化一个对象,什么时候不需要?

import java.io.*; 
class ShowFile 
{ 
    public static void main(String args[]) 
    throws IOException 
    { 
     int i; 
     FileInputStream fin; 
     try 
     { 
      fin=new FileInputStream(args[0]); 
     } 
     catch(FileNotFoundException e) 
     { 
      System.out.println("File not found"); 
     } 
     catch(ArrayIndexOutOfBoundsException e) 
     {System.out.println("Array index are out of bound");} 
     do 
     { 
      i=fin.read(); 
      System.out.println((char) i); 
     } while(i!=-1); 
     fin.close(); 
    } 
} 

,但在下面的代码,我没有得到这样的错误

import java.io.*; 

class ShowFile { 
    public static void main(String args[]) 
    { 
    int i; 
    FileInputStream fin; 

    // First, confirm that a file name has been specified. 
    if(args.length != 1) { 
     System.out.println("Usage: ShowFile filename"); 
     return; 
    } 

    // Attempt to open the file. 
    try { 
     fin = new FileInputStream(args[0]); 
    } catch(FileNotFoundException e) { 
     System.out.println("Cannot Open File"); 
     return; 
    } 

    // At this point, the file is open and can be read. 
    // The following reads characters until EOF is encountered. 
    try { 
     do { 
     i = fin.read(); 
     if(i != -1) System.out.print((char) i); 
     } while(i != -1); 
    } catch(IOException e) { 
     System.out.println("Error Reading File"); 
    } 

    // Close the file. 
    try { 
     fin.close(); 
    } catch(IOException e) { 
     System.out.println("Error Closing File"); 
    } 
    } 
} 

为什么会这样?请帮帮我。对于阅读不便,感到抱歉。这是我的第一篇文章,所以我不知道如何发布。

谢谢。

+0

阅读变量初始化在这里:http://stackoverflow.com/questions/1560685/why-must-local-variables-including-primitives-always-be-initialized-in-java – Drejc 2014-11-22 16:36:36

+0

两者之间的区别:你在第二种情况下('return;')出现检查异常时退出该方法,保证没有对'fin'的读取访问权限,在第一种情况下,您只需执行do-while循环( - >读取访问将会发生)。 – fabian 2014-11-22 16:46:52

+0

谢谢fabian。但在第一种情况下返回后,仍然收到相同的错误:“ShowFile1.java:21:错误:变量fin可能未初始化 i = fin.read(); ^ 1错误” – 2014-11-22 17:11:41

回答

0

你有这样的try-catch

try { 
    fin=new FileInputStream(args[0]); 
} catch(...) { 
..... 
} 

,你赶上一个潜在的FileNotFoundException然后之外的它您在访问fin

如果第一个块中出现异常,那么鳍会初始化并且您将以NPE结束

将读数移到第一个块内。

try { 
    fin=new FileInputStream(args[0]); 
    do { 
     i=fin.read(); 
     System.out.println((char) i); 
    } while(i!=-1); 
} catch(...) { 
..... 
} finally { 
    if(fin != null) { 
     try { fin.close(); } catch(IOException e) {} 
    } 
} 
+0

非常感谢。我清楚地理解了这个概念。感谢您的明确解释:) – 2014-12-04 08:43:41

0

变量在使用前需要初始化。 例如,对于您的情况,例如,此行fin=new FileInputStream(args[0]);可能会引发异常(假设文件不存在),则捕获该异常并将其打印出来,然后执行此操作i=fin.read(); 此处fin可能尚未初始化。

一般情况下,它总是初始化所有的变量是一个好主意,当你声明它们:

int i = 0; 
InputStream fin = null; 

下一次,也请您发布需要帮助的实际的错误信息。它有助于不必尝试从精神上“编译”你的代码来猜测你在说什么。

+0

感谢您的帮助迪马:)。下次我也会发布实际的错误。 – 2014-11-22 16:55:50

0

对于在方法中声明和未初始化的变量,从声明到变量使用的任何点都不能有任何可能的执行路径。这由编译器检查,它不会让你compule。

类中的字段总是初始化的,可能为零,所以它不适用于这些。

相关问题