我一直得到一个空指针异常

时间:2013-11-02 18:19:08

标签: java

我正在制作一个图书馆程序,记录集合中的任何书籍以及每本书的副本数量。这是代码

import java.util.Arrays;
import java.util.Scanner;
public class Library{
  static String title;
  static String author;
  static int id;
  static int copies;
  static String date;
  static Book[] database = new Book[100];
  static int count=0;

  public static void main(String[] args){
    int i;
    Scanner s = new Scanner(System.in);
    do{
      addBook();
      System.out.println("would you like to add another book?");
      i=s.nextInt();
    }while(i == 0);
    database[0].viewDetails();
    database[1].viewDetails();
    checkingOut();
  }
  public static void addBook(){
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the title of the book you want to add to the collection");
    title=s.nextLine();
    System.out.println("Enter the author of the book you want to add to the collection");
    author=s.nextLine();
    System.out.println("Enter the publishing date of the book you want to add to the collection");
    date=s.nextLine();
    System.out.println("Enter the ID number of the book you want to add to the collection");
    id=s.nextInt();
    System.out.println("Enter the the number of copies that will be added into the collection");
    copies=s.nextInt();

    Book Book1 = new Book(date, author, copies, id, title);
    database[count] = Book1;
    count++;
  }
  public static void checkingOut(){
    boolean found=false;
    int idSearch;
    int i=0;
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the ID number of the book you want to check out");
    idSearch=s.nextInt();
    while(i<database.length && found!=true){
      if(database[i].getIdentificationNumber() == idSearch){
        found = true;
      }
      i++;
    }
    if(found==true){
      database[i].checkOut();
      System.out.println("There are "+database[i].getNumberCopies()+" copies left");
    }
    else{System.out.println("There is no book with that ID number!");}
  }
}

我在检出方法的第55行得到一个空指针异常,我无法弄清楚原因。如果您能发现任何帮助将非常感谢,请告诉我。

3 个答案:

答案 0 :(得分:1)

if(found=true)将始终执行,因为赋值的表达式返回赋值,这将导致database[i].checkOut();在不应该执行的地方执行。

你应该写:

if(found)

这就是我们在比较==时避免写boolean的原因。写if(someBoolean)就足够了。

答案 1 :(得分:0)

发现== true,not found = true

答案 2 :(得分:0)

应为if(found==true)

而不是=使用===将始终评估为true