In: Computer Science
Write a OOP class called BookList that uses a Book class and allows multiple books to be entered into a BookList object. Include normally useful methods and boolean addBook(Book b), Book searchBook(String title, String author). addBook returns true if b is successfully added to the list. searchBook returns a book matching either the title or author from the current list. You do not need to write Book (assume there are suitable constructors and methods) or any test code (main). You can write them if you wish. Use Java or other language if you wish; use any IDE or compiler.
//C++ programming
#include<iostream>
using namespace std;
class Book{
private:
string title;
string author;
Book *next;
public:
Book(){
title =
"";
author =
"";
next =
NULL;
}
Book(string t , string a){
title = t;
author =
a;
next =
NULL;
}
void setTitle(string t){
title= t;
}
void setAuthor(string a){
author =
a;
}
void setNext(Book*n){
next = n;
}
string getTitle(){
return
title;
}
string getAuthor(){
return
author;
}
Book* getNext(){
return
next;
}
~Book(){
}
};
class BookList{
private:
Book *head;
public:
BookList(){
head =
NULL;
}
bool addBook(Book *b){
if(head==NULL){
head = b;
return true;
}
Book *current =
head;
while(current->getNext()!=NULL)current =
current->getNext();
current->setNext(b);
return
true;
}
Book* searchBook(string title,
string author){
if(head==NULL)return NULL;
Book *current =
head;
while(current){
if(current->getTitle()==title ||
current->getAuthor()==author)return current;
current = current->getNext();
}
return
NULL;
}
};
int main(){
BookList list;
string title,author;
int choice;
do{
cout<<"1:Add Book\n2:Search
Book\n3:Quit\n";
cin>>choice;
switch(choice){
case 1:{
cout<<"Enter title : ";
cin.get();
getline(cin,title);
cout<<"Enter author : ";
getline(cin,author);
Book*b = new Book(title,author);
if(list.addBook(b))cout<<"Book
Added\n";
else cout<<"Book not added\n";
break;
}
case 2:{
cout<<"Enter title : ";
cin.get();
getline(cin,title);
cout<<"Enter author : ";
getline(cin,author);
Book*b = list.searchBook(title,author);
if(!b)cout<<"Book not found\n";
else cout<<"Book found\n";
break;
}
case 3:{
cout<<"\nThank you\n";
break;
}
default:{
cout<<"Invalid Input\n";
break;
}
}
}while(choice!=3);
return 0;
}
//sample output