Reputation: 37
It is showing temp_lib is not declared, but it is already declared.
Library temp_lib is already declared after try and return, temp_lib is written at last but also it is asking for me to initialize the variables.
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;
Upvotes: 1
Views: 238
Reputation: 393936
Library temp_lib;
must be before the try-catch block in order to be in scope after the try-catch block.
Library temp_lib = null; // you must give it an initial value, or the code
// won't compile
try {
...
}
catch (..) {
...
}
return temp_lib;
Upvotes: 3