I have an assignment to make this Restaurant Program. it Consists of an Order Class a product class and the main class. Order has an ArrayList to hold the products. I create an instance of the Order and then I add items through my main method.A product has a name(string) a bar-code(string), and a price(float).
Then I have to output a receipt.But what if a customer orders more of one product? Do I instantiate everything one by one? Is a second Beer Product independent? Should I hold quantities somehow? If I want to add a second beer I have to create a new product Beer2 etc? I don't know beforehand how many products each order will hold and the quantity of each so Is this way of instantiating proper? Thanks
Note: it is still incomplete as I want to deal with this before I move on.
import java.util.Date;
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer);
order1.add(Beef);
System.out.println(order1.getReceipt(30f));
}
}
Order Class(nevermind the name Paraggelia I gave it)
import java.util.ArrayList;
import java.util.Date;
/*Notes to self:
* -Work on Comments
* -Javadocs maybe?
* -try to optimize the rough code.
*/
/*Order class*/
public class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private ArrayList<Product> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new ArrayList<Product>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.add(p);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(int i =0; i<this.listOfItems.size();i++){
receipt.append(listOfItems.get(i).getName());
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
Product Class:
public class Product {
private String Name;
private String barCode;
private float sellingPrice;
/*Constructors: */
Product(){}
Product(String Name,String barCode,float sellingPrice){
this.Name=Name;
this.barCode=barCode;
this.sellingPrice=sellingPrice;
}
/*Getters & Setters*/
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public float getSellingPrice() {
return sellingPrice;
}
public void setSellingPrice(float sellingPrice) {
this.sellingPrice = sellingPrice;
}
}
Instead of ArrayList ( List ) you can use Map ( HashMap for example )
MyRestaurantTester
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer, 1);
order1.add(Beef, 5);
System.out.println(order1.getReceipt(30f));
}
}
Paraggelia
class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private Map<Product, Integer> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new HashMap<Product, Integer>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p, int quantity){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.put(p, quantity);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(Map.Entry<Product,Integer> entry : this.listOfItems.entrySet()) {
Product product = entry.getKey();
Integer quantity = entry.getValue();
receipt.append(product.getName() + " " + quantity);
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
OUTPUT:
Pork Beef 5
Amstel 1
Three basic approaches come to mind:
Instantiate each product individually
Instead of ArrayList, have another structure that can associate items with quantities; or,
Make a class Article, which belongs to a Product: Product beerProduct = new Product("beer", "0129", 1.37); Article beer = new Article(beerProduct), beer2 = new Article(beerProduct).
The first solution gives you a lot of flexibility (e.g. to discount individual articles for, say, being damaged). The second solution is more economical with objects. The third one captures the intuition that all the Heineken bottles are the same. It is really up to what you want to do - both approaches are equally valid, for some purpose.
Related
Doing my homework, and trying to get some values to spit out onto a table in IntelliJ right now. I'm following a webinar series, and can't figure out what I'm doing wrong. I try to add a part to the system, but I get an error that "non-static method addPart(classes.Part) cannot be referenced from a static context." Along with three other errors around the same area in my MainApplication.java file.
package project.wfc482project;
import classes.InHouse;
import classes.Outsourced;
import classes.Part;
import classes.Inventory;
import classes.Product;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class MainApplication extends Application {
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("MainMenu.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 320, 240);
stage.setTitle("C482 Inventory Management System");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
// Sample values, Parts, and Products
InHouse inhouse1 = new InHouse(1, "Tire", 10.99, 10, 0, 20, 125);
InHouse inhouse2 = new InHouse(2, "Strut", 12.99, 27, 0, 30, 124);
Outsourced outsourced1 = new Outsourced(3, "Tubing", 7.50, 5, 0, 15, "Super Parts");
Outsourced outsourced2 = new Outsourced(5, "Lens", 3.50, 22, 0, 25, "Auto Glass");
Inventory.addPart(inhouse1);
Inventory.addPart(inhouse2);
Inventory.addPart(outsourced1);
Inventory.addPart(outsourced2);
launch();
// Call static members
}
}
And here's the Inventory.java page that I am trying to pull from, which pulls from a Parts.java page that I'll throw up here in a sec...
package classes;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Inventory {
private static int partId = 0;
private static int productId = 0;
private static ObservableList<Part> allParts = FXCollections.observableArrayList();
private static ObservableList<Product> allProducts = FXCollections.observableArrayList();
public static ObservableList<Part> getAllParts() {
return allParts;
}
public ObservableList<Product> getAllProducts() {
return allProducts;
}
public void addPart(Part newPart) {
allParts.add(newPart);
}
public void addProduct(Product newProduct) {
allProducts.add(newProduct);
}
public static int getNewPartId() {
return ++partId;
}
public static int getNewProductId() {
return ++productId;
}
public Part lookupPart(int partId) {
Part partFound = null;
for (Part part : allParts) {
if (part.getId() == partId) {
partFound = part;
}
}
return partFound;
}
public ObservableList<Part> lookupPart(String partName) {
ObservableList<Part> partsFound = FXCollections.observableArrayList();
for (Part part : allParts) {
if (part.getName().equals(partName)) {
partsFound.add(part);
}
}
return partsFound;
}
public Product lookupProduct(int productId) {
Product productFound = null;
for (Product product : allProducts) {
if (product.getId() == productId) {
productFound = product;
}
}
return productFound;
}
public ObservableList<Product> lookupProduct(String productName) {
ObservableList<Product> productsFound = FXCollections.observableArrayList();
for (Product product : allProducts) {
if (product.getName().equals(productName)) {
productsFound.add(product);
}
}
return productsFound;
}
public void updatePart(int index, Part selectedPart) {
allParts.set(index, selectedPart);
}
public void updateProduct(int index, Product selectedProduct) {
allProducts.set(index, selectedProduct);
}
public boolean deletePart(Part selectedPart) {
if (allParts.contains(selectedPart)) {
allParts.remove(selectedPart);
return true;
}
else {
return false;
}
}
public boolean deleteProduct(Product selectedProduct) {
if (allProducts.contains(selectedProduct)) {
allProducts.remove(selectedProduct);
return true;
}
else {
return false;
}
}
}
The Part Class:
package classes;
public abstract class Part {
// Declare fields
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
// Declare Constructor
public Part(int id, String name, double price, int stock, int min, int max) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
this.min = min;
this.max = max;
}
public Part() {
}
// Setters and Getters
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the price
*/
public double getPrice() {
return price;
}
/**
* #param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* #return the stock
*/
public int getStock() {
return stock;
}
/**
* #param stock the stock to set
*/
public void setStock(int stock) {
this.stock = stock;
}
/**
* #return the min
*/
public int getMin() {
return min;
}
/**
* #param min the min to set
*/
public void setMin(int min) {
this.min = min;
}
/**
* #return the max
*/
public int getMax() {
return max;
}
/**
* #param max the max to set
*/
public void setMax(int max) {
this.max = max;
}
}
And the InHouse class:
package classes;
public class InHouse extends Part{
private int machineId;
public InHouse(int id, String name, double price, int stock, int min, int max, int machineId) {
super(id, name, price, stock, min, max);
this.machineId = machineId;
}
public int getMachineId() {
return machineId;
}
public void setMachineId(int machineId) {
this.machineId = machineId;
}
}
I've tried looking up answers to this on here and Reddit, but I'm having a hard time making sense of it all.
I understand that I can't make a part for an abstract class, although that's what the webinar tells me to do (it's more likely that that's what I'm interpreting that as, but I'm turned around and not understanding it).
Change the method Inventory.addPart() to a static method. Change this:
public void addPart(Part newPart) {
allParts.add(newPart);
}
to this
public static void addPart(Part newPart) {
allParts.add(newPart);
}
Following is stretagy design pattern example take from here.
First of all we will create the interface for our strategy, in our case to pay the amount passed as argument.
public interface PaymentStrategy {
public void pay(int amount);
}
public class CreditCardStrategy implements PaymentStrategy {
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
this.name=nm;
this.cardNumber=ccNum;
this.cvv=cvv;
this.dateOfExpiry=expiryDate;
}
#Override
public void pay(int amount) {
System.out.println(amount +" paid with credit/debit card");
}
}
public class PaypalStrategy implements PaymentStrategy {
private String emailId;
private String password;
public PaypalStrategy(String email, String pwd){
this.emailId=email;
this.password=pwd;
}
#Override
public void pay(int amount) {
System.out.println(amount + " paid using Paypal.");
}
}
public class Item {
private String upcCode;
private int price;
public Item(String upc, int cost){
this.upcCode=upc;
this.price=cost;
}
public String getUpcCode() {
return upcCode;
}
public int getPrice() {
return price;
}
}
public class ShoppingCart {
//List of items
List<Item> items;
public ShoppingCart(){
this.items=new ArrayList<Item>();
}
public void addItem(Item item){
this.items.add(item);
}
public void removeItem(Item item){
this.items.remove(item);
}
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum += item.getPrice();
}
return sum;
}
public void pay(PaymentStrategy paymentMethod){
int amount = calculateTotal();
paymentMethod.pay(amount);
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
//pay by paypal
cart.pay(new PaypalStrategy("myemail#example.com", "mypwd"));
//pay by credit card
cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
}
}
I want to ask what is use of strategy pattern here?Once we have created a strategy in main.We have access to Strategy class now.We can directly call pay() method from there?Why do we need interface , all which does is call a method?
1. I want to ask what is use of strategy pattern here?
The answer is the user who has the ShoppingCart (ShoppingCart cart = new ShoppingCart();)
2. We can directly call pay() method from there?
I don't know exactly you mean
3. Why do we need interface , all which does is call a method?
We need the interface PaymentStrategy because we need use Polymorphism to implement many way to pay (paypal or credit card), let's change the source a bit and you can see clearer:
public class ShoppingCart {
// other functions
public void pay(PaymentStrategy paymentMethod, int amount){
paymentMethod.pay(amount);
}
public void payWithStrategy() {
int amount = calculateTotal();
if (amount > 10000) { // because your credit card limit is 10000$ so you must use paypal
pay(new PaypalStrategy("myemail#example.com", "mypwd"), amount);
}
else { // you really like credit card so when the money lower than the card limit, you always choose it
pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"), amount);
}
}
}
public class ShoppingCartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Item item1 = new Item("1234",10);
Item item2 = new Item("5678",40);
cart.addItem(item1);
cart.addItem(item2);
cart.payWithStrategy();
}
}
I'm trying to add static methods largest and smallest to the Measurable interface.
The methods should return the object with the largest or smallest measure (double) from an array of Measurable Country objects. I tried doing so in the interface, but someone recommended me using the Comparator interface. How can this be done by using the Measurable interface instead?
class Main {
public static void main(String args[]) {
Measurable[] countries = new Measurable[3];
countries[0] = new Country("Uruguay", 176220);
countries[1] = new Country("Thailand", 514000);
countries[2] = new Country("Belgium", 30510);
Measurable maximum = Measurable.largest(countries);
Measurable smallest = Measurable.smallest(countries);
}
}
class Country implements Measurable {
private String name;
private double area;
public Country(String name, double area) {
this.name = name;
this.area = area;
}
}
interface Measurable {
static Measurable largest(Measurable[] countries) {
public static Measurable largest(Measurable[]objects){
if (objects == null || objects.length == 0) {
return new Country("", 0);
}
Measurable max = new Country("", 0);
for (Measurable obj : objects) {
if (obj.getMeasure() > max.getMeasure()) {
max = obj;
}
}
return max;
}
}
static Measurable smallest(Measurable[] objects) {
if (objects == null || objects.length == 0) {
return new Country("", 0);
}
Measurable max = new Country("", 0);
for (Measurable obj : objects) {
if (obj.getMeasure() < min.getMeasure()) {
min = obj;
}
}
return min;
}
}
double getMeasure();
}
You don't need to create the Measurable interface if you want to use Comparator/Comparable.
Just implement Comparable in Country and then loop through the array to find min and max.
class Main {
public static void main(String args[]) {
Country[] countries = new Country[3];
countries[0] = new Country("Uruguay", 176220);
countries[1] = new Country("Thailand", 514000);
countries[2] = new Country("Belgium", 30510);
Country max = null;
Country min = null;
for (Country c : countries) {
if (max == null || max.compareTo(c) < 0) {
max = c;
}
if (min == null || min.compareTo(c) > 0) {
min = c;
}
}
System.out.printf("max: %s (%s)%n", max.name, max.area);
System.out.printf("min: %s (%s)%n", min.name, min.area);
}
}
class Country implements Comparable<Country> {
String name;
double area;
public Country(String name, double area) {
this.name = name;
this.area = area;
}
#Override
public int compareTo(Country other) {
// Returns int <0 if this is smaller than other
// 0 if they are equal
// int >0 if this is greater than other
return Double.compare(this.area, other.area);
}
}
If you put your countries in a collection you can use the Collections.min() and Collections.max() functions together with the Comparable interface. Your main method would then look like this:
public static void main(String args[]) {
List<Country> countries = new ArrayList<>();
countries.add(new Country("Uruguay", 176220));
countries.add(new Country("Thailand", 514000));
countries.add(new Country("Belgium", 30510));
Country max = Collections.max(countries);
Country min = Collections.min(countries);
System.out.printf("max: %s (%s)%n", max.name, max.area);
System.out.printf("min: %s (%s)%n", min.name, min.area);
}
If you still want to use the Measurable interface you can extend ArrayList and have that class implement it like this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Main {
public static void main(String args[]) {
CountryList countries = new CountryList();
countries.add(new Country("Uruguay", 176220));
countries.add(new Country("Thailand", 514000));
countries.add(new Country("Belgium", 30510));
Country max = countries.getLargest();
Country min = countries.getSmallest();
System.out.printf("max: %s (%s)%n", max.name, max.area);
System.out.printf("min: %s (%s)%n", min.name, min.area);
}
}
class CountryList extends ArrayList<Country> implements Measurable{
#Override
public Country getSmallest() {
return Collections.min(this);
}
#Override
public Country getLargest() {
return Collections.max(this);
}
}
interface Measurable{
Country getSmallest();
Country getLargest();
}
class Country implements Comparable<Country> {
String name;
double area;
public Country(String name, double area) {
this.name = name;
this.area = area;
}
#Override
public int compareTo(Country o) {
return Double.compare(this.area, o.area);
}
}
I've been working on my add method for a couple of hours now and seem to have hit a roadblock. My method is supposed to search through every node in the list to see if there is a matching employee number and if there isn't, add the object in order of employee number.
Unfortunately I cant even seem to add a node to the beginning or end of my list. I think I understand the logic. I have to search through my list for find where I want the node, then all I have to do is have the new node's link point the already existing one. I think that I'm either not creating the nodes properly or not linking them properly. Every time I try to test my code though, only one node appears in my list.
import java.util.*;
public class HumanResources
{
private EmployeeNode first;
employee data = new employee();
private class EmployeeNode
{
//data members of employeenode
private EmployeeNode link;
employee data = new employee();
private EmployeeNode()
{
data = null;
link = null;
}
private EmployeeNode (employee emp)
{
data = emp;
link = null;
}
}
public EmployeeNode search (employee search)
{
EmployeeNode current = first;
if (first == null)
{ return null;}
while((present != null) && (present.data != search))
{
present = present.link;
}
return present;
}
private EmployeeNode nextInList(EmployeeNode x)
{
return x.link;
}
public boolean isEmpty()
{
return ( first == null );
} // end of isEmpty()
public HumanResources()
{
first = null;
}
public HumanResources ( employee x)
{
this.data = x;
}
public boolean addEmployee( employee emp)
{
EmployeeNode current = new EmployeeNode();
current = first;
if (current == null)
{
first = new EmployeeNode(emp);
return true;
}
else
{
while(current.link != null)
{
EmployeeNode temp = new EmployeeNode();
temp.data = emp;
temp.link = current;
}
return true;
}
}
public Employee findEmployee(String EmpNumber)
{
EmployeeNode current = first;
if(first == null)
{
return null;
}
else{
while (current != null)
{
public String toString()
{
EmployeeNode display;
display = first;
String temp = "";
while(display != null)
{
temp += display.data + "\n";
display = display.link;
}
return temp;
}
}
And here is my employee class
import java.util.*;
/**
This class manipulate information relating to employees
*/
public class employee {
private String empNumber;
private String name;
private String department;
private double salary;
/**
Zero parameter constructor that sets the values to null
*/
public employee()
{
empNumber = null;
name = null;
department = null;
salary = 0.0;
}
/**
Four parameter constructor to initialize the data members to the give values
#param kempnumber Employee's ID number
#param kname Employee's name
#param kdepartment Employee's department name
#param ksalary Employee's salary
*/
public employee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
/**
copy constructor
*/
public employee (employee copy)
{
empNumber = copy.empNumber;
name = copy.name;
department = copy.department;
salary = copy.salary;
}
/**
Four parameter constructor to set data members to given value
#param kname Employee's name
#param kdepartment Employee's department name
#param ksalary Employee's salary
*/
public void setEmployee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
public String getEmpNumber() {
return empNumber;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary)
{
this.salary = salary;
}
public String toString()
{
return (empNumber + " " + name + " " + department + " " +salary);
}
public boolean equals(employee compareto) {
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if (firstemployee == secondemployee) {
return true;
}
else {
return false;
}
}
public int compareTo(employee compareto)
{
int less = -1;
int same = 0;
int more = 1;
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if(firstemployee > secondemployee)
{
return more;
}
else if(firstemployee == secondemployee)
{
return same;
}
else
{
return less;
}
}
}
For the addEmployee method, if you are adding to the front of the list you shouldn't need a while loop at all. Your 'first' variable is presumably maintaining a reference to the front of the loop, so all you need to do is create the employee, update the links and point 'first' towards it. Something like this...
public boolean addEmployee( employee emp){
if (first == null) {
first = new EmployeeNode(emp);
return true;
}
else { // first must != null
EmployeeNode temp = new EmployeeNode(emp); //create the new employee
temp.link = first; // link the new employee to the old employee at the front of the list
first = temp; //update the new front of list to be the new employee
return true;
}
}
Keep in mind though if you want to add it to the end of the list, you will need a while loop to search through the list and find the end before creating the new employee and updating the links.
If your getting confused with the links, try stepping through the code and drawing out the nodes with lines to represent the links to help get you used to visualising the linked list.
Basically I have multiple classes and I'm trying to get an array of LineItem for each Item that a customer purchases. LineItem includes the UPC, Description, Price, Quantity, SubTotal and Discount which is all stored in a seperate class. I'm trying to get it that when you use the method addItemToSaleList it will add to the array. I need to use an array and not an array list, so I have to copy over the array to a temp array, and then recreate a new array adding to the number the array can store and then recopying it over. I'm stuck getting the array to generate. Below is the code I have
public class Product {
private double price;
private String description;
private String ProductCode;
private DiscountStrategy discoutStrategy;
public Product(double price, String description, String ProductCode, DiscountStrategy discoutStrategy) {
this.price = price;
this.description = description;
this.ProductCode = ProductCode;
this.discoutStrategy = discoutStrategy;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProductCode() {
return ProductCode;
}
public void setProductCode(String ProductCode) {
this.ProductCode = ProductCode;
}
public DiscountStrategy getDiscountStrategy() {
return discoutStrategy;
}
public void setDiscoutStrategy(DiscountStrategy discoutStrategy) {
this.discoutStrategy = discoutStrategy;
}
}
public class LineItem {
private Product product;
private double quantity;
public LineItem(Product product, double quantity) {
this.product = product;
this.quantity = quantity;
}
//Calculates the Discount Amount whether or not it's a percentage or dollar
//off
public double getDiscountAmount () {
return product.getDiscountStrategy().getDiscount(product.getPrice(), quantity);
}
//Calculates the Subtotal, gets the quantity from the DiscountStrategy and then
//the price from the product
public double getSubTotal() {
return quantity * product.getPrice();
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public class Receipt {
private LineItem[] lineItem = new LineItem[0];
public Receipt(LineItem[] lineItem) {
this.lineItem = lineItem;
}
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = new LineItem[tempItemList.length];
for (int j = 0; j < lineItem.length; j++) {
lineItem[j] = tempItemList[j];
}
}
public LineItem[] getLineItem() {
return lineItem;
}
I would remove addItemToSaleList() and implement addProductToTotalSale(LineItem) like so
public void addProductToTotalSale(LineItem li) {
// Allocate the memory.
LineItem[] tempLineItem = new LineItem[1 + lineItem.length];
// Copy the array.
if (lineItem.length > 0) {
System.arraycopy(lineItem, 0, tempLineItem, 0, lineItem.length);
}
// add the new item to the new slot.
tempLineItem[lineItem.length] = li;
// update the internal array reference.
lineItem = tempLineItem;
}
Next, you should protect your constructor from null;
public Receipt(LineItem[] lineItem) {
// Try and protect from bad calls, removes need to check for nulls in
// add (addProductToTotalSale) routine.
if (lineItem != null) {
this.lineItem = lineItem;
}
}
Because you provide a default 0 sized array your code appears to be safe to continue to include the default constructor. But, you might consider making your Receipt class immutable.
I'm not sure why you are making two new arrays. You only need one...
public void addProductToTotalSale(LineItem li) {
addItemToSaleList();
lineItem[lineItem.length-1] = li;
}
public void addItemToSaleList() {
LineItem[] tempItemList = new LineItem[lineItem.length + 1];
for (int i = 0; i < tempItemList.length; i++) {
tempItemList[i] = lineItem[i];
}
lineItem = tempItemList;
}