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)
import java.util.Scanner;
import java.io.*;
class Product {
int
pid;
String
pname;
double
price;
int
qty;
public
Product(int pid, String pname, double price, int qty) {
this.pid = pid;
this.pname = pname;
this.price = price;
this.qty = qty;
}
public
double calculateTotal() {
return price * qty;
}
public
void displayProduct() {
System.out.println("Product ID: " + pid);
System.out.println("Product Name: " + pname);
System.out.println("Price: $" + price);
System.out.println("Quantity: " + qty);
}
}
public class ProductDemo {
public
static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of products: ");
int numProducts = scanner.nextInt();
Product[] products = new Product[numProducts];
for (int i = 0; i < numProducts; i++) {
System.out.println("Enter details for product #" + (i + 1));
System.out.print("Product ID: ");
int pid = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Product Name: ");
String pname = scanner.nextLine();
System.out.print("Price: $");
double price = scanner.nextDouble();
System.out.print("Quantity: ");
int qty = scanner.nextInt();
products[i] = new Product(pid, pname, price, qty);
}
System.out.println("Product Details:");
double totalAmount = 0;
for (Product product : products) {
product.displayProduct();
double productTotal = product.calculateTotal();
System.out.println("Total Amount for this product: $" +
productTotal);
totalAmount += productTotal;
System.out.println();
}
System.out.println("Total Amount for all products: $" +
totalAmount);
}
}