A bookshelf is designed to store the books in a stack with LIFO (Last In First Out) operation. Define a class Book with the following specifications:
Class name: Book
Data members/instance variables:
name[]: stores the names of the books
point: stores the index of the topmost book
max: stores the maximum capacity of the bookshelf
Methods/Member functions:
Book(int cap): constructor to initialize the data members max = cap and point = -1
void tell(): displays the name of the book which was last entered in the shelf. If there is no book left in the shelf, displays the message “SHELF EMPTY”
void add(String v): adds the name of the book to the shelf if possible, otherwise displays the message “SHELF FULL”
void display(): displays all the names of the books available in the shelf
Specify the class Book giving the details of only the functions void tell() and void add(String). Assume that the other functions have been defined.
The main() function need not be written.
import java.util.Scanner;
class Book{
String name[];
int point;
int max;
public Book(int cap){
max = cap;
point = -1;
name = new String[max];
}
public void tell(){
if(point == -1)
System.out.println("SHELF EMPTY");
else
System.out.println("LAST ENTERED: " + name[point]);
}
public void add(String v){
if(point + 1 == max)
System.out.println("SHELF FULL");
else
name[++point] = v;
}
public void display(){
if(point == -1)
System.out.println("SHELF EMPTY");
else{
System.out.println("BOOKS AVAILABLE:");
for(int i = 0; i <= point; i++)
System.out.println(name[i]);
System.out.println();
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Bookshelf capacity: ");
int cap = Integer.parseInt(in.nextLine());
Book stack = new Book(cap);
while(true){
System.out.println("1. Last entered book");
System.out.println("2. Add book");
System.out.println("3. Display all books");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(in.nextLine());
switch(choice){
case 1:
stack.tell();
break;
case 2:
System.out.print("Name of the book: ");
String n = in.nextLine();
stack.add(n);
break;
case 3:
stack.display();
break;
default:
System.out.println("Bye!");
return;
}
}
}
}