// Define the Product class
class Product {
private String name;
private double price;
private int quantity;
private double taxRate; // Tax rate as a decimal (e.g., 0.08 for 8%)
// Constructor to initialize the product
public Product(String name, double price, int quantity, double taxRate) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.taxRate = taxRate;
}
// Method to calculate the total cost including tax
public double calculateTotalCost() {
double subtotal = price * quantity;
double taxAmount = subtotal * taxRate;
double totalCost = subtotal + taxAmount;
return totalCost;
}
// Getters and setters (optional based on requirements)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getTaxRate() {
return taxRate;
}
public void setTaxRate(double taxRate) {
this.taxRate = taxRate;
}
}
// Main class to demonstrate the product calculation
public class ProductCalculation {
public static void main(String[] args) {
// Create a product instance
Product product = new Product("Smartphone", 999.99, 2, 0.08); // Example values: price, quantity, tax rate
// Calculate the total cost including tax
double totalCost = product.calculateTotalCost();
// Display the result
System.out.println("Product: " + product.getName());
System.out.println("Price per unit: $" + product.getPrice());
System.out.println("Quantity: " + product.getQuantity());
System.out.println("Tax rate: " + (product.getTaxRate() * 100) + "%");
System.out.println("Total cost (including tax): $" + totalCost);
}
No comments:
Post a Comment