1

Im a beginner in java and im trying to use an array i've created but it keep not recoginze it. anyone know what could be the thing im missing here ?

to be more specific the command bookArray.length is making this error.

Library(int maxBookCapacity){
    Book bookArray[]= new Book[libraryMaxBookCapacity];
}

boolean inLibrary(Book book){
    for(int i=0; i<bookArray.length; i++ ){
        if (book==bookArray[i]){
            return true;
        }
    }
    return false;
}

2 Answers 2

1

bookArray is a local variable and spocannot be access outside of the defining method. In fact local means just that: that the name bookArray is only available inside the constructor.

If you need it in inLibrary you should declare is as a field in the enclosing class:

public class Library {

  private final Book[] bookArray;

  public Library(int maxBookCapacity){
    bookArray = new Book[libraryMaxBookCapacity];
  }

  public boolean inLibrary(Book book){
    for(int i = 0; i < bookArray.length; i++ ){
      if (book == bookArray[i]){
        return true;
      }
    }
    return false;
  }
}

By the way, consider if you actually need to compare book objects with the == operator.

Sign up to request clarification or add additional context in comments.

Comments

0
// If you declare this within the constructor, it'll be a local variable and nobody can access it. 
// Having it here means that inLibrary can see it
private Book[] bookArray;

Library(int maxBookCapacity){
    // watch out here, in your code you have a different var from the parameter of the constructor
    bookArray= new Book[maxBookCapacity];
}

boolean inLibrary(Book book){
    for(int i=0; i<bookArray.length; i++ ){
        if (book==bookArray[i]){
            return true;
        }
    }
    return false;
}

Comments

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.