Jump to content

search in an arraylist

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Minky

Minky

    Newbie

  • Members
  • Pip
  • 5 posts
Hi! I'm having trouble understanding how to search in an arraylist of objects that concists of multiple Strings and Integers and an arraylist.

For example, I have created the classes Author, Book and CollectionOfBooks. One book can hold many authors and a CollectionOfBooks can hold multiple books. I've managed to search after book-titles, isbn etc, but I can't get it to work when i want to search for an author in a CollectionOfBooks.

The code below is how I search for an author, but I keep getting NullPointerException =/

CollectionOfBooks.java
public Book getBooksByAuthor(String author) {

		Collections.sort(Books);

		for (int i = 0; i < Books.size(); i++) {

			if (Books.get(i).stringAuthor().equals(author)) {

				return Books.get(i);

			}

		}

		return null;

	}

Book.java
public String stringAuthor() {

		String temp = "";

		for (int i = 0; i < Author.size(); i++) {

			temp = temp + Author.get(i);

			if (i > 0 && i < (Author.size() - 1)) {

				temp = temp + ", ";

			}

		}

		return temp;

	}

UI.java
public void getBooksByAuthor() {

		System.out.print("Search for Author: ");

		Scanner scan = new Scanner(System.in);

		String Author = scan.nextLine();

		Book temp = cob.getBooksByAuthor(Author);

		System.out.println("Books found : " + cob.toString(temp));


	}



I've added the whole code below just to clarify what I mean.

Author.java
package se.kth.labb3b;


import java.io.Serializable;


@SuppressWarnings("serial")

public class Author implements Serializable {

	private String name;


	public Author(String n){

		name = n;

	}

	

	public String getAuthor(){

		return name;

	}

}

Book.java
//Skapar skelett


package se.kth.labb3b;


import java.io.Serializable;

import java.util.ArrayList;


@SuppressWarnings("serial")

public class Book implements Comparable<Book>, Serializable {


	private String title;

	private int edition, isbn;

	private double price;


	private ArrayList<Author> Author = new ArrayList<Author>();


	public Book(String title, int isbn, int edition, double price, ArrayList<Author> Author) {

		this.title = title;

		this.isbn = isbn;

		this.edition = edition;

		this.price = price;

		this.Author = Author;

	}


	public String getTitle() {

		return title;

	}


	public int getIsbn() {

		return isbn;

	}


	public int getEdition() {

		return edition;

	}


	public double getPrice() {

		return price;

	}


	public ArrayList<Author> getAuthors() {

		return Author;

	}


	public String stringAuthor() {

		String temp = "";

		for (int i = 0; i < Author.size(); i++) {

			temp = temp + Author.get(i);

			if (i > 0 && i < (Author.size() - 1)) {

				temp = temp + ", ";

			}

		}

		return temp;

	}


	public int compareTo(Book other) {

		return this.title.compareTo(other.title);

	}


}

CollectionOfBooks.java
package se.kth.labb3b;


import java.util.ArrayList;

import java.util.Collections;


public class CollectionOfBooks {


	private ArrayList<Book> Books = new ArrayList<Book>();


	public void addBook(Book book) {

		Books.add(book);

		Collections.sort(Books);


	}


	public void removeBook(Book book) {

		Books.remove(book);

	}


	public int getNumberOfBooks() {

		return Books.size();

	}


	public Book getBooksByTitle(String title) {

		Collections.sort(Books);

		for (int i = 0; i < Books.size(); i++) {

			if (Books.get(i).getTitle().equals(title)) {

				return Books.get(i);

			}

		}

		return null;

	}


	public Book getBooksByIsbn(int isbn) {

		Collections.sort(Books);

		for (int i = 0; i < Books.size(); i++) {

			if (Books.get(i).getIsbn() == (isbn)) {

				return Books.get(i);

			}

		}

		return null;

	}


	public Book getBooksByEdition(int edition) {

		Collections.sort(Books);

		for (int i = 0; i < Books.size(); i++) {

			if (Books.get(i).getEdition() == (edition)) {

				return Books.get(i);

			}

		}

		return null;

	}


	public Book getBooksByPrice(double price) {

		Collections.sort(Books);

		for (int i = 0; i < Books.size(); i++) {

			if (Books.get(i).getPrice() == (price)) {

				return Books.get(i);

			}

		}

		return null;

	}


	public Book getBooksByAuthor(String author) {

		Collections.sort(Books);

		for (int i = 0; i < Books.size(); i++) {

			if (Books.get(i).stringAuthor().equals(author)) {

				return Books.get(i);

			}

		}

		return null;

	}


	public ArrayList<Book> remoteSort() {

		return Books;

	}


	public String toString(int i) {

		String back;

		System.out.println("**************************************");

		back = ("Title: " + Books.get(i).getTitle());

		back = back + "\nISBN: " + Integer.toString(Books.get(i).getIsbn());

		back = back + "\nRevision: " + Integer.toString(Books.get(i).getEdition());

		back = back + "\nPrice: " + Double.toString(Books.get(i).getPrice());

		back = back + "\nAuthor: \n";

		ArrayList<Author> author = Books.get(i).getAuthors();

		for (int j = 0; j < author.size(); j++) {

			back = back + "\t" + author.get(j).getAuthor() + "\n";

		}

		System.out.println("**************************************");

		return back;

	}


	public String toString(Book temp) {

		String back;

		System.out.println("**************************************");

		back = ("Title: " + temp.getTitle());

		back = back + "\nISBN: " + Integer.toString(temp.getIsbn());

		back = back + "\nRevision: " + Integer.toString(temp.getEdition());

		back = back + "\nPrice: " + Double.toString(temp.getPrice());

		back = back + "\nAuthor: \n";

		ArrayList<Author> author = temp.getAuthors();

		for (int j = 0; j < author.size(); j++) {

			back = back + "\t" + author.get(j).getAuthor() + "\n";

		}

		System.out.println("**************************************");

		return back;

	}

}

UI.java
package se.kth.labb3b;


import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.ObjectInput;

import java.io.ObjectInputStream;

import java.io.ObjectOutput;

import java.io.ObjectOutputStream;

import java.io.OutputStream;

import java.io.Serializable;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;



@SuppressWarnings("serial")

public class UI implements Serializable {


	Book books;

	CollectionOfBooks cob = new CollectionOfBooks();


	public void addBook() {

		System.out.print("Book name: ");

		Scanner scan = new Scanner(System.in);

		String bookName = scan.nextLine();

		System.out.print("ISBN: ");

		int isbn = scan.nextInt();

		System.out.print("Edition: ");

		int edition = scan.nextInt();

		System.out.print("Price: ");

		double price = scan.nextDouble();

		ArrayList<Author> lista = new ArrayList<Author>();

		System.out.print("Numbers of authors: ");

		int numberOfAuthors = scan.nextInt();

		for (int i = 0; i <= numberOfAuthors; i++) {

			System.out.println("Author: ");

			lista.add(new Author(scan.nextLine()));

		}

		books = new Book(bookName, isbn, edition, price, lista);

		cob.addBook(books);


	}

	

	public void readBook(Book book){

		cob.addBook(book);

	}


	public void getBooksByTitle() {

		System.out.print("Search for title: ");

		Scanner scan = new Scanner(System.in);

		String title = scan.nextLine();

		Book temp = cob.getBooksByTitle(title);

		System.out.println("Books found : " + cob.toString(temp));


	}

	

	public void getBooksByIsbn() {

		System.out.print("Search for ISBN: ");

		Scanner scan = new Scanner(System.in);

		int isbn = scan.nextInt();

		Book temp = cob.getBooksByIsbn(isbn);

		System.out.println("Books found : " + cob.toString(temp));


	}

	

	public void getBooksByEdition() {

		System.out.print("Search for Edition: ");

		Scanner scan = new Scanner(System.in);

		int edition = scan.nextInt();

		Book temp = cob.getBooksByIsbn(edition);

		System.out.println("Books found : " + cob.toString(temp));


	}

	

	public void getBooksByAuthor() {

		System.out.print("Search for Author: ");

		Scanner scan = new Scanner(System.in);

		String Author = scan.nextLine();

		Book temp = cob.getBooksByAuthor(Author);

		System.out.println("Books found : " + cob.toString(temp));


	}

	

	public void getBooksByPrice() {

		System.out.print("Search for Price: ");

		Scanner scan = new Scanner(System.in);

		double price = scan.nextInt();

		Book temp = cob.getBooksByPrice(price);

		System.out.println("Books found : " + cob.toString(temp));


	}

	

	public void getAllBooks() {

		System.out.println("Book titles: \n");

		for (int j = 0; j < cob.getNumberOfBooks(); j++) {

			System.out.print(cob.toString(j));

		}


	}

	

	public void writeToFile(){

		List<Book> temp = cob.remoteSort();

	    try{

	        //use buffering

	        OutputStream file = new FileOutputStream( "books.dat" );

	        OutputStream buffer = new BufferedOutputStream( file );

	        ObjectOutput output = new ObjectOutputStream( buffer );

	        try{

	          output.writeObject(temp);

	        }

	        finally{

	          output.close();

	        }

	      }  

	      catch(IOException e){

	        e.printStackTrace();

	      }


	}

	

	public void readFromFile(){

 //note the use of abstract base class references

	    

	    try{

	      //use buffering

	      InputStream file = new FileInputStream( "books.dat" );

	      InputStream buffer = new BufferedInputStream( file );

	      ObjectInput input = new ObjectInputStream ( buffer );

	      try{

	        //deserialize the List

	        @SuppressWarnings("unchecked")

			List<Book> recoveredBooks = (List<Book>)input.readObject();

	        //display its data

	        for(Book book: recoveredBooks){

	        //  System.out.println("Recovered books: " + book);

	          readBook(book);

	        }

	      }

	      finally{

	        input.close();

	      }

	    }

	    catch(ClassNotFoundException e){

	      e.printStackTrace();

	    }

	    catch(IOException e){

	      e.printStackTrace();

	      System.out.println("File books.dat wasn't found!");

	    }


	}

	

}


UserInterface.java
//Skapar skelett


package se.kth.labb3b;


import java.util.Scanner;


public class UserInterface {


	public static void main(String[] args) {

		UI ui = new UI();

		int running = 1;

		

		int runOnce=1;

		while(runOnce==1){

			ui.readFromFile();

			runOnce=0;

		}

		

		while (running == 1) {

			System.out.println("**************************************");

			System.out.println("**************************************");

			System.out.println("Welcome to Lars and Daniels bookrecord!\n\n" + 

					"1) Add a new book\n" + 

					"2) List all objects\n" +

					"3) Search for books\n" +

					"4) Write to file\n" +

					"5) Exit");

			System.out.println("**************************************");

			System.out.println("**************************************");

			

			Scanner scan = new Scanner(System.in);

			int answer = scan.nextInt();

			switch (answer) {

			case 1:

				ui.addBook();

				break;

			case 2:

				ui.getAllBooks();

				break;

			case 3:

				System.out.println("**************************************");

				System.out.println("1) Search books by title\n" +

						"2) Search books by ISBN\n" +

						"3) Search books by Edition\n" +

						"4) Search books by Price\n" +

						"5) Search books by Author\n");

				System.out.println("**************************************");

				int answer2 = scan.nextInt();

				switch(answer2){

				case 1:

					ui.getBooksByTitle();

					break;

				case 2:

					ui.getBooksByIsbn();

					break;

				case 3:

					ui.getBooksByEdition();

					break;

				case 4:

					ui.getBooksByPrice();

					break;

				case 5:

					ui.getBooksByAuthor();

					break;

				default:

					System.out.println("Opps!");

					break;

				}

				

				break;

			case 4:

				ui.writeToFile();

				break;

			case 5:

				System.out.println("Ciao!");

				System.exit(0);

			default:

				System.out.println("Fail");

				running = 0;

				break;


			}

		}


	}

}


Any help would be appreciated =)

#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
NullPointerException occurs, when you are trying to modify object, which doesn't exist. (reference to nowhere)
For example getBooksByAuthor() might return null, if no book is found. If you are certain, that book should be found, then print out all the variables used for comparison, and see what's wrong. For example the stringAuthor() in your Book class seems to return something very weird and i'm not sure if this should be used for comparison with a single author.

Always, when looking for a bug: print, print and print. All the variables used. That will help you a lot.

#3
Minky

Minky

    Newbie

  • Members
  • Pip
  • 5 posts
Ah yes, the stringAuthor is the problem, but I don't have a clue how to fix it...What you refer to as "very weird" is not that weird i think, if you look at the toString, you'll see how I parse it. But the question is why it doesn't work =/

#4
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
Well, the program is too big for me to build up in my mind, but i understand the idea.

Books.get(i).stringAuthor().equals(author)
does author and stringAuthor match as Strings? your stringAuthor returns something like "Dan Brown, Hemingway". Is the author String you are passing also "Dan Brown, Hemingway"? or are you passing just one author?
What if you accidentally pass the authors other way around as "Hemingway, Dan Brown"? it certainly won't match it then.

I would suggest you make a containsAuthor(Author author) method in your Book class, which returns boolean. and variables and fields are lowerCamelCase. So change your ArrayList Author to author

public boolean containsAuthor(Author author){
      return this.author.contains(author)
}
your method:
public Book getBooksByAuthor(String author) 
should be rewritten (and ArrayList Books should be lowerCamelCase again):

public ArrayList<Book> getBooksByAuthor(Author author){
     ArrayList<Book> booksTemp = new ArrayList<Book>();
     for(Book book: books){
           if(book.containsAuthor(author)) booksTemp.add(book);
     }
     return booksTemp;
}
So it returns all the books written by that author, not only one.

After that, Author class must implement equals(Object o) method
public boolean equals(Object o){
     if(o instanceof Author){
           return ((Author)o).getAuthor().equals(name);
     }
     return false;
}
Java convention:
All classes are HighCamelCase. All methods, variables and fields are lowerCamelCase.

example:
ArrayList myList = new ArrayList();