Slip no 17 Q B

Q.Define a class Product (pid, pname, price, qty). Write a function to accept the product details, display it and calculate total amount. (use array of Objects) [25 M]

import java.util.Scanner;

class Product
{
    int pid;
    String pname;
    double price;
    int qty;

    // Function to accept product details
    void accept()
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Product ID: ");
        pid = sc.nextInt();

        System.out.print("Enter Product Name: ");
        pname = sc.next();

        System.out.print("Enter Price: ");
        price = sc.nextDouble();

        System.out.print("Enter Quantity: ");
        qty = sc.nextInt();
    }

    // Function to calculate total amount
    double calculate()
    {
        return price * qty;
    }

    // Function to display product details
    void display()
    {
        System.out.println(pid + "\t" + pname + "\t" + price + "\t" + qty + "\t" + calculate());
    }
}

class ProductDemo
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of products: ");
        int n = sc.nextInt();

        Product p[] = new Product[n];

        // Create objects
        for(int i = 0; i < n; i++)
        {
            p[i] = new Product();
            System.out.println("\nEnter details of product " + (i+1));
            p[i].accept();
        }

        // Display details
        System.out.println("\nPID\tName\tPrice\tQty\tTotal");
        for(int i = 0; i < n; i++)
        {
            p[i].display();
        }
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top