1

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;
1
  • 2
    temp_lib is declared within the try block, and you're trying to use it outside the try block. (Perhaps some proper indentation would make it clearer.) Commented Jun 7, 2015 at 9:50

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

1 Comment

@Nachinne_Manche did you give it an initial value? (see edit)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.