2013-11-02 32 views
0

我正在制作一个库程序,用来保存集合中任何书籍的记录以及每本书的副本数量。下面是代码我不断收到一个空指针异常

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行空指针异常,我无法找出原因。请让我知道,如果你能发现它的任何帮助将不胜感激。

+2

哪条线会抛出NPE? –

+0

第57行.....我的程序虽然有另一个问题。在我的添加书籍方法中,有没有办法制作新的书籍对象?我的意思是每次运行方法制作book1,然后是第二次book2,然后book3 .....等等。因为现在当我尝试添加新书时,基本上只是重新设置了我为前一本书所做的信息。 –

+0

我如何知道哪一行是第57行?你希望我计算57行代码吗?你能不能把某种形式的标记或者告诉我们这个特定的线上有什么? –

回答

0

发现== TRUE,未找到=真

1

if(found=true)将总是执行,因为分配的表达式返回分配值,和这将导致database[i].checkOut();被执行,其中它不应该。

你应该写:

if(found)

这就是为什么我们避免编写==当我们比较boolean秒。编写if(someBoolean)就足够了。

0

应该是if(found==true)

代替=使用===将始终评估为true

+0

谢谢你们,这是一个愚蠢的错误,不能相信我无法发现。 –

+0

虽然我的程序遇到了另一个问题。在我的添加书籍方法中,有没有办法制作新的书籍对象?我的意思是每次运行方法制作book1,然后是第二次book2,然后book3 .....等等。因为现在当我尝试添加新书时,基本上只是重新设置了我为前一本书所做的信息。 –