显示未声明temp_lib,但已经声明了它。
库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;
答案 0 :(得分: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;