[英]I keep getting a null pointer exception
我正在制作一個圖書館程序,該程序會記錄館藏中的所有書籍以及每本書的副本數。 這是代碼
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行收到空指針異常,我不知道為什么。 請讓我知道,如果您能發現它有什么幫助,將不勝感激。
因為賦值的表達式返回分配的值 ,所以將始終執行if(found=true)
,這將導致database[i].checkOut();
在不應該執行的地方執行。
您應該寫:
if(found)
這就是為什么在比較boolean
s時避免寫==
的原因。 編寫if(someBoolean)
足夠了。
發現==真,未發現=真
應該是if(found==true)
代替=
使用==
as =
將始終評估為true
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.