
Hi I've made an array of Book objects that I made, the array is called library and it can hold 100 books, but currently there are 6. The Book objects contain three private strings; an author, a title and a short summary. A Book object also contains the appropriate constructor and getters and setters. Now I've made a method to search for a given string in a given field and it returns a string called results, but when I try run it, it gives me a NullPointerException. The code is shown below, please help:
protected static Book[] library=new Book[100];
public String searchLibrary(int field,String param){
String result = "";
String strfield = "";
int counter=0;
switch(field){
case 1: strfield=library[counter].getAuthor();
break;
case 2: strfield=library[counter].getTitle();
break;
case 3: strfield=library[counter].getDdc();
break;
}
while(library[counter]!=null){
if(strfield.contains(param)){
result+=library[counter].toString()+"\n";
}
counter++;
}
return result;
}

Ah I just figured out my error, sorry guys. What a simple mistake, I feel retarded.

You can also try the following code:
import java.util.*;
class Book{
String author;
String title;
String summary;
public Book(String author,String title,String summary){
this.author=author;
this.title=title;
this.summary=summary;
}
public String getTitle(){
return title;
}
public String getAuthor(){
return author;
}
public String getSummary(){
return summary;
}
}
public class BookInformation{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
Book myLibrary[]=new Book[6];
for(int i=0;i<myLibrary.length;i++){
System.out.print("Author: ");
String author=input.nextLine();
System.out.print("Title: ");
String title=input.nextLine();
System.out.print("Summary: ");
String summary=input.nextLine();
myLibrary[i]=new Book(author,title,summary);
System.out.println();
}
System.out.println();
System.out.println("Book Information");
for (int i = 0; i < myLibrary.length; i++){
Book library = myLibrary[i];
System.out.println(library.getAuthor() + "\t "+ library.getTitle() + "\t "+ library.getSummary() + "\t ");
}
System.out.println();
System.out.print("Enter title to search infomation: ");
String tit=input.nextLine();
System.out.println();
for(int i = 0; i < myLibrary.length; i++) {
if(tit.equals(myLibrary[i].getTitle())) {
System.out.println("Author is: "+myLibrary[i].getAuthor());
System.out.println("Summary is: "+myLibrary[i].getSummary());
}
}
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.