1

I've created a small program where I have an array of 100 strings (null unless value added using another function).

If I am trying to issue a book that is not in the array, it is giving me NullPointerException error, instead of not running the if statement and printing that book isn't found.

public void issueBook() {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter book title to issue: ");
    String BookTitle = sc.nextLine();           //Asks for book name to be compared in the array
    for (int i = 0; i < Books.length; i++) {    //loop to check
        if (this.Books[i].equals(BookTitle)) {  //if statement to check the condition
            System.out.println("Book has been issued.");
            this.Books[i] = null; //If the book has been issued, it will null it's position in the array
            return;
            }
        }
        System.out.println("ERROR: Book not found.");   //If the book isn't found, it should print this
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
brownputin
  • 79
  • 5
  • You can simply change `this.Books[i].equals(BookTitle)` to `BookTitle.equals(this.Books[i])` – Holger Mar 15 '21 at 11:52

2 Answers2

3

If this.Books is populated with null at least initially, than you need to check that this.book[i] is not null before calling any of its methods or you will get those NullPointerExceptions:

for (int i = 0; i < this.Books.length; i++) {
    if (this.Books[i] != null && this.Books[i].equals(BookTitle)) {
        // do something...
    }
}

I would suggest that you use an ArrayList instead. This way you can simply add the books as they are created, and you would never need deal with a NullPointerException when pulling from the this.Books variable because only a fully created book will be appended to the list.

joshmeranda
  • 3,001
  • 2
  • 10
  • 24
2
public void issueBook(String[] Books) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter book title to issue: ");
    String BookTitle = sc.nextLine();           //Asks for book name to be compared in the array
    for (int i = 0; i < Books.length; i++) {    //loop to check
        if (this.Books[i]!= null && this.Books[i].equals(BookTitle)) {  //if statement to check the condition
            System.out.println("Book has been issued.");
            this.Books[i] = null; //If the book has been issued, it will null it's position in the array
            return;
            }
        }
        System.out.println("ERROR: Book not found.");   //If the book isn't found, it should print this
    }