Monday, 10 February 2025

Write java application to define book class containing BookId, Title, author, rate, number of copies. Define parameterized constructor. Define method that will calculate cost of books. Accept details of five books in array of object from user display details along with cost of all books.

import java.util.Scanner;


// Define Book class

class Book {

    int bookId;

    String title;

    String author;

    double rate;

    int numCopies;


    // Parameterized constructor

    Book(int bookId, String title, String author, double rate, int numCopies) {

        this.bookId = bookId;

        this.title = title;

        this.author = author;

        this.rate = rate;

        this.numCopies = numCopies;

    }


    // Method to calculate total cost of books

    double calculateCost() {

        return rate * numCopies;

    }


    // Method to display book details

    void displayDetails() {

        System.out.println("Book ID: " + bookId);

        System.out.println("Title: " + title);

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

        System.out.println("Rate: " + rate);

        System.out.println("Number of Copies: " + numCopies);

        System.out.println("Total Cost: " + calculateCost());

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

    }

}


// Main class

public class BookStore {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        Book[] books = new Book[5]; // Array of book objects


        // Accept details of five books

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

            System.out.println("Enter details for Book " + (i + 1) + ":");

            System.out.print("Enter Book ID: ");

            int bookId = scanner.nextInt();

            scanner.nextLine(); // Consume newline

            System.out.print("Enter Title: ");

            String title = scanner.nextLine();

            System.out.print("Enter Author: ");

            String author = scanner.nextLine();

            System.out.print("Enter Rate: ");

            double rate = scanner.nextDouble();

            System.out.print("Enter Number of Copies: ");

            int numCopies = scanner.nextInt();


            // Create Book object and store in array

            books[i] = new Book(bookId, title, author, rate, numCopies);

        }


        // Display details of all books

        System.out.println("\nBook Details:");

        for (Book book : books) {

            book.displayDetails();

        }


        scanner.close();

    }

}