A
Anonymous

Order Form - Copy this React, Tailwind Component to your project

//EXERCISE 4 import java.util.ArrayList; import java.util.Scanner; public class Item { private int id; private String name; private double price; // Constructor to initialize an item public Item(int id, String name, double price) { this.id = id; this.name = name; this.price = price; } // Getter for ID public int getId() { return id; } // Setter for ID public void setId(int id) { this.id = id; } // Getter for name public String getName() { return name; } // Setter for name public void setName(String name) { this.name = name; } // Getter for price public double getPrice() { return price; } // Setter for price public void setPrice(double price) { this.price = price; } } class Order { private int id; private ArrayList<Item> items; // Constructor to initialize the order with an ID public Order(int id) { this.id = id; this.items = new ArrayList<>(); } // Getter for ID public int getId() { return id; } // Setter for ID public void setId(int id) { this.id = id; } // Getter for the items in the order public ArrayList<Item> getItems() { return items; } // Setter for items public void setItems(ArrayList<Item> items) { this.items = items; } // Method to add an item to the order public void addItem(Item item) { items.add(item); } // Method to calculate the average cost of the items in the order public double calculateAverageCost() { double totalCost = 0; for (Item item : items) { totalCost += item.getPrice(); } if (items.size() > 0) { return totalCost / items.size(); } else { return 0; } } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Get order ID from the user System.out.print("Enter the order ID: "); int orderId = scanner.nextInt(); // Create a new order Order order = new Order(orderId); // Get the number of items in the order System.out.print("Enter the number of items: "); int numItems = scanner.nextInt(); // Loop to add items to the order for (int i = 0; i < numItems; i++) { System.out.println("Enter details for item " + (i + 1) + ":"); // Get item ID System.out.print("Item ID: "); int itemId = scanner.nextInt(); // Get item name System.out.print("Item Name: "); String itemName = scanner.next(); // Get item price System.out.print("Item Price: "); double itemPrice = scanner.nextDouble(); // Create an item and add it to the order Item item = new Item(itemId, itemName, itemPrice); order.addItem(item); } // Calculate and display the average cost of the order double averageCost = order.calculateAverageCost(); System.out.println("Average cost of the order: " + averageCost); scanner.close(); } }

Prompt
Component Preview

About

OrderForm - Create and manage orders with item details, average cost calculation, and user input. Built with React and Tailwind. Copy code today!

Share

Last updated 1 month ago