InterviewSolution
| 1. |
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 initialise 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 on 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. |
|
Answer» import java.io.*; 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 { for(int i = 0; i <= point; i++) System.out.println(name[i]); } } public static void main(String args[])throws IOException { InputStreamReader input = new InputStreamReader(System.in); BufiferedReader br = new BufferedReader(input); System.out.print("Capacity of the bookshelf: "); int size = Integer.parseInt(br.readLine()); Book obj = new Book(size); loop: while(true) { System.out.println("1. Last Entered"); System.out.println("2. Add New"); System.out.println("3. List All"); System.out.print("Enter your choice: "); int choice = Integer.parseInt(br.readLine()); switch(choice) { case 1: obj.tell(); break; case 2: System.out.print("Book title:"); String title=br.readLine(); obj.add(title); break; case 3: obj.display(); break; default: break loop; } } } } |
|