2014-11-22 65 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。

類中的字段總是初始化的,可能爲零,所以它不適用於這些。

相關問題