[英]I keep getting a null pointer exception
I'm making a library program that keeps a record of any books that are in the collection and how many copies of each book there are. 我正在制作一个图书馆程序,该程序会记录馆藏中的所有书籍以及每本书的副本数。 Here is the code
这是代码
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!");}
}
}
I'm getting a null pointer exception on line 55 of my checking out method, I can't figure out why. 我在检出方法的第55行收到空指针异常,我不知道为什么。 Please let me know if you can spot what it is any help would be greatly appreciated.
请让我知道,如果您能发现它有什么帮助,将不胜感激。
if(found=true)
will be always executed because the expression of the assignment returns the assigned value , and this will cause database[i].checkOut();
因为赋值的表达式返回分配的值 ,所以将始终执行
if(found=true)
,这将导致database[i].checkOut();
to be executed where it shouldn't. 在不应该执行的地方执行。
You should write: 您应该写:
if(found)
That's why we avoid writing ==
when we compare boolean
s. 这就是为什么在比较
boolean
s时避免写==
的原因。 It's enough to write if(someBoolean)
. 编写
if(someBoolean)
足够了。
发现==真,未发现=真
should be if(found==true)
应该是
if(found==true)
instead of =
use ==
as =
will always evaluate as true
. 代替
=
使用==
as =
将始终评估为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.