Hello guys, i m working on a program that stores details of a book collection. Following are the things that should be there:

•	Write a new class ‘book’ to represent details of special book objects. A book consists of (for example) the title, number of copies, author, (“The Davinci Code”, 5, “Brown”). 
•	 Your class definition should include an appropriate constructor method, and methods to allow addition, updating, searching and sorting of objects. 
•	The class should have a method to store all the objects from the array into a file. A further method should allow the contents of a previously stored file of objects to be restored into an array. 
•	Create a menu of options for the programme including
o	Input a new object from a keyboard
o	Search for an object and print details to screen 
o	Edit an object
o	Sort the objects 
o	Print all the entries so far
o	Save objects to a file
o	Retrieve objects from a file
o	Quit

Now i have done the book class in which i have the private fields, constructor, get and set methods and i have done the library class which is somewhat incomplete because i don't understand how to proceed.

Here is my book class.

import java.util.*;
public class Book {

    private String title;
    private int bookNo;
    private String author;
    private int noOfCopies;
    
    public Book(String t,String a, int bN, int nOC)
    {
    	title = t;
    	bookNo = bN;
    	author = a;
    	noOfCopies = nOC;
    }
    
    public Book()
    {
    	title = "";
    	bookNo = 0;
    	author = "";
    	noOfCopies = 0;
    }
    
   
//Return the title of this book	
	public String getTitle()
	{
		return title;
	}
//Return the number of copies of this book
	public int getNoOfCopies()
	{
		return noOfCopies;
	}
//Return the book number of this book
	public int getBookNo()
	{
		return bookNo;
	}
//Return the author of this book
	public String getAuthor()
	{
		return author;
	}
// Set the title of this book to the given string
	public void setTitle(String t)
	{
		title = t;
	}
// Set the number of copies of this book to the given integer
	public void setNoOfCopies(int nOC)
	{
		noOfCopies = nOC;
	}
// set the book number of this book to the given integer
	public void setBookNo(int b)
	{
		bookNo = b;
	}
// set the author of this book to the given String
	public void setAuthor(String a)
	{
		author = a;
	}
	
	/*public boolean equals(String t)
	{
		boolean equals = false;
		if(title.equals(t)) {
			equals = true;
		}
		return equals;
	} // IGNORE THIS METHOD*/
	
	
    
}

Following is my library class with adding, updating, searching and writing to file methods. The booksort is incomplete.

/**
 * An example of a library class which holds an array of books 
 * and an indicator pointing to the next available slot in the array
 
 */
import java.io.*; 
import java.util.*;
import javax.swing.JOptionPane; 
public class Library 
{
	final int SIZE = 20;
	Book[] books = new Book[SIZE]; //The array can hold maximum of 20 book records
    int bookIndex = 0;

//Method to add book objects which can be called from the main method if the user wishes to add details of a book, i.e. create a new object in class book.
    public void addBook() 
    {
        Book b = new Book();
        b.setTitle((JOptionPane.showInputDialog("What is the title?")));
        b.setNoOfCopies((Integer.parseInt(JOptionPane.showInputDialog("What is the number of copies?"))));
    	b.setBookNo((Integer.parseInt(JOptionPane.showInputDialog("What is the book number?"))));
    	b.setAuthor((JOptionPane.showInputDialog("What is the author")));
        books[bookIndex] = b;
        bookIndex++;
    }
    
//Method to update fields of a book object    
    public void updateBook()
    {
    	int index = Integer.parseInt(JOptionPane.showInputDialog("Please enter the index number of the book you would like to update"));
    	books[index] = new Book();
    	books[index].setTitle(JOptionPane.showInputDialog("Enter the Title"));
    	books[index].setNoOfCopies(Integer.parseInt(JOptionPane.showInputDialog("Enter the number of copies?")));
    	books[index].setBookNo(Integer.parseInt(JOptionPane.showInputDialog("Enter the book number?")));
    	books[index].setAuthor(JOptionPane.showInputDialog("Enter the author?"));
    }
    
//Method to search for an object    
    public static int linearSearch(Book [] data, int key, int sizeOfArray)
 	{
   		for (int counter = 0; counter < sizeOfArray; counter++)
   		{
			if (data[counter].getBookNo() == key)
				return counter; // return position where found
   		}	

   		return -1; // if drop off end of array, its not there
 	}

	
//Method to write to a file
	public void writeBook()throws IOException
    {
    	String filename = JOptionPane.showInputDialog("Please enter a file name to add the book details in.");
    	FileWriter outputFile = new FileWriter(filename);
   	    BufferedWriter outputBuffer = new BufferedWriter(outputFile);
        PrintWriter printStream = new PrintWriter(outputBuffer); 
        	
        Book temp = new Book();
        temp = books[bookIndex];	
        printStream.println(temp.getTitle());
        printStream.println(temp.getNoOfCopies());
        printStream.println(temp.getBookNo());
        printStream.println(temp.getAuthor());
        
        printStream.close();		
    } 	
	
	public void bookSort()
	{
		
	}
}

AND finally this is the main class which is very much incomplete. Please help me, when i run the main class and enter the addbook details, and later when i try to search for the book just added, it gives me error. Also please tell me how to do the sort method and the rest.

import javax.swing.*;
public class Example {

    public static void main(String[] args) 
    {

        int option = 1;
        System.out.println("Enter 1 to add a book");
        System.out.println("Enter 2 to search for a book");
        while(option!=-1)
        {
        
        String str = JOptionPane.showInputDialog("Enter an option");
        option = Integer.parseInt(str);
        Library pp = new Library();
        switch(option) 
        {
            case 1:
                pp.addBook();
                break;
            
            case 2:
            	int k = Integer.parseInt(JOptionPane.showInputDialog("Enter the book number of the book to search for"));
       		    pp.linearSearch(pp.books,k,pp.SIZE);
       		    break;    
        }
        }
    }
}

KINDLY HELP.

Don't do the requirements in order. You should zoom in on requirement 9 (print all the entries so far). This will help you in debugging. Don't waste time searching and sorting until you know for sure that the adding and displaying is working. Garbage in, garbage out. If it isn't stored correctly and doesn't display correctly, you can't display results and you can't search and you can't sort. So enter in some already sorted entries and display them. Make sure that works. Does it?

Regarding the search and sort, a linear search is a brute force method, but fairly easy to write. The easiest sort to write is Bubble Sort. To do a sort, you'll need to decide what exactly makes an object bigger than another object and you'll need to write a swap function probably.

Comments
Wise advice

Thanks a lot Vernon, that might help a lot actually, but can you please help me out more regarding the code and provide me with the searching and sorting by book number. Thanks.

This link has an implementation of bubble sort in Java. If you look at the bubble sort code, all you need to do to adapt it to your needs is modify it so that it compares your book numbers and so that it swaps your book objects. Two simple modifications.

In order to do a search, you should write an equals() method in your book class that returns "true" if two books are the same and returns false otherwise. This link shows you the general idea of how to implement equals(), but in your case it will be even simpler because if two books have the same number they are probably the same book. If the method I just described to you is too hard to write, then just write a for loop like this:

for (int i = 0; i < array.length; i++){
if (book.bookNo == array[i].bookNo){
//you found your book, do something
}
}

And keep in mind our rules - we try to keep code samples limited.

Edited 6 Years Ago by BestJewSinceJC: n/a

Thanks a lot Vernon, that might help a lot actually, but can you please help me out more regarding the code and provide me with the searching and sorting by book number. Thanks.

Yes, when you get to that point, we can help. But my point is that you aren't there yet, so it's premature to do that. You need to confirm that your "add" and "display" functions work first before you touch the sorting and searching functions. You can't confirm that "add" works until you write the "display" function first. When that's all written and works, THEN worry about sorting and searching.

public void displayBook()
    {
       	for (int i=0;i<SIZE;i++)
    	{
    		JOptionPane.showMessageDialog(null,"Entry for book number "+i+" :"+"\n"+books[i].getTitle()+"\n"+books[i].getNoOfCopies()
    			                                 +"\n"+books[i].getBookNo()+"\n"+books[i].getAuthor());
    	}
    	
    }

Heres my displaybook method as vernon said, but ir gives me an error if i try to execute from main method:

Exception in thread "main" java.lang.NullPointerException
    at Library.displayBook(Library.java:32)
    at Example.main(Example.java:25)

And heres main.

import javax.swing.*;
public class Example {

    public static void main(String[] args) 
    {

        int option = 1;
        System.out.println("Enter 1 to add a book");
        System.out.println("Enter 2 to display books");
        System.out.println("Enter 3 to search for books");
        while(option!=-1)
        {
        
        String str = JOptionPane.showInputDialog("Enter an option");
        option = Integer.parseInt(str);
        Library pp = new Library();
        switch(option) 
        {
            case 1:
                pp.addBook();
                break;
               
            case 2:
            	pp.displayBook();
            	break;    
            
            case 3:
            	int k = Integer.parseInt(JOptionPane.showInputDialog("Enter the book number of the book to search for"));
       		    pp.linearSearch(pp.books,k,pp.SIZE);
       		    break;    
        }
        }
    }
}

You should point to the line where the error is. The message says lines 25 and 32, but make sure that you point out what line number that corresponds to in your POSTING. It might be the same line number, might not.

Regardless, it's fairly clear what is wrong here, or at least ONE thing that is wrong. No guarantee that it is the ONLY thing wrong. Look at your loop:

for (int i=0;i<SIZE;i++)

Look at your declaration.

final int SIZE = 20;

Do you have 20 books? If not, you can't display twenty books and you're going to get a null pointer exception. SIZE represents the MAXIMUM number of books that can be stored. You want the ACTUAL number of books that are in your array.

Edited 6 Years Ago by VernonDozier: n/a

Thanks a lot VernonDozier because of you my problem is almost solved and i have got everything to run except my linear search and bubblesort. Need to do that sooner or later.

THANKS A LOT, THIS FORUM IS VERY HELPFUL AND VernonDozier has solved my problem by explaining "You need to confirm that your "add" and "display" functions work first before you touch the sorting and searching functions.".

This article has been dead for over six months. Start a new discussion instead.