如何在我的迷你库程序中获取没有 NullPointerException 的 else 语句?

How to get to the else statement without NullPointerException in my mini library program?

我创建了一个小程序,其中有一个包含 100 个字符串的数组(除非使用其他函数添加值,否则为空)。

如果我尝试发行一本不在数组中的书,它会给我 NullPointerException 错误,而不是 运行 if 语句并打印那本书未找到。

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
    }

如果 this.Books 至少在最初用 null 填充,那么您需要在调用它的任何方法之前检查 this.book[i] 是否不为空,否则您将得到那些 NullPointerExceptions:

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

我建议您改用 ArrayList。通过这种方式,您可以在创建书籍时简单地添加它们,并且在从 this.Books 变量中提取时,您永远不需要处理 NullPointerException,因为只有完全创建的书籍才会附加到列表中。

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
    }