2015-06-07 23 views
1

它顯示temp_lib沒有聲明,但它已經聲明。在java中未定義的變量try catch return語句

函數庫temp_lib已經在try和return之後聲明,temp_lib是最後編寫的,但它也要求我初始化變量。

int numAdded=0; 
File inputfile; 

inputfile = new File("export_Library.txt"); 
try { 
    Library temp_lib; 
    Scanner inputScanner = new Scanner(inputfile); 
    System.out.println("processing a library..."); 
    String name=inputScanner.nextLine(); 
    int capacity=Integer.parseInt(inputScanner.next()); 
    temp_lib=new Library(name,capacity); 

    LibraryItem item=new LibraryItem(); 
    while(inputScanner.hasNextLine()){ 
     item.setTitle(inputScanner.nextLine()); 
     item.setID_code(inputScanner.nextLine()); 
     item.setYearOfPublication(Integer.parseInt(inputScanner.nextLine())); 
     if(inputScanner.next()=="1") 
     { 
      item.setOnLoan(true); 
     } 
     else 
     { 
      item.setOnLoan(false); 
     } 
     item.setReplacementCost(inputScanner.nextDouble()); 
    } 
    inputScanner.close(); 
} 
catch (IOException e) { 
    System.out.println("IO Exception reading shapes from file"+e); 
    e.printStackTrace() ; 
    //return temp_lib; 
} 
return temp_lib; 
+2

''temp_lib'在''try'塊內被聲明*,並且你試圖在'try'塊之外使用它*。 (也許一些正確的縮進會使它更清晰。) – Biffen

回答

3

Library temp_lib;必須try-catch塊之前,爲了在範圍在try-catch塊之後。

Library temp_lib = null; // you must give it an initial value, or the code 
         // won't compile 
try { 
    ... 
} 
catch (..) { 
    ... 
} 
return temp_lib; 
+0

已經嘗試過,但沒有工作 –

+0

@Nachinne_Manche你給它初始值嗎? (見編輯) – Eran

+0

謝謝你工作.... –