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);
}
Related
I understand that I do not have anything in my main method yet so nothing will execute, that is the second part to the assignment.
My question is, I'm getting an error in the computeDiscount method where I'm calling the computeNumCases method. The error i'm getting is
variable numCases might not have been initialized
so I need help figuring that error out.
Also, help in the computeCost method would be very helpful as well.
public class Customer {
private String customerLastName;
private String candyType;
private int numCandyBars;
private double costPerBar;
private int NUMBERPERCASE = 12;
public static void main(String[] args) {
}
public Customer() {
}
public Customer(String name, String type, int numCandyBars, double costPerBar) {
//this.name = name;
candyType = type;
this.numCandyBars = numCandyBars;
this.costPerBar = costPerBar;
}
public static double getCostPerBar(double costPerBar) {
return costPerBar;
}
public static int getNumCandyBars(int numCandyBars) {
return numCandyBars;
}
public String getCandyType() {
return candyType;
}
public String GetCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String name) {
this.customerLastName = name;
}
public void setNumCandyBars(int num) {
this.numCandyBars = num;
}
public void setCandyType(String candyType) {
this.candyType = candyType;
}
public void setCostPerBar(double cost) {
costPerBar = cost;
}
public int computeNumCases(int numCases) {
numCases = numCandyBars / NUMBERPERCASE;
return numCases;
}
public int computeNumIndividuals(int numIndividuals) {
numIndividuals = numCandyBars % NUMBERPERCASE;
return numIndividuals;
}
public int computeDiscount(int discount) {
int numCases = computeNumCases(numCases);
if (numCases < 20)
discount = 100;
else if (numCases < 50)
discount = 85;
else
discount = 75;
return discount;
}
public double computeCost(double totalCost) {
return computeNumCases(numCases) * getCostPerBar(costPerBar) * (NUMBERPERCASE * discount / 100.00) + computeNumIndividuals(numIndividuals) * getCostPerBar(costPerBar);
}
}
I am making a text-based game on JavaFX, and after I hit a tree, I want to get Oak logs.
I have already built my inventory, and I have put default items in it such as Water, Bread, etc.
I am trying to add my Oak Logs to my inventory, but nothing is working.
Here is a part of my code:
Item ItemList[] = {new Bread(), new OakLog()};
Optional<ButtonType> result = alert.showAndWait();
if(result.get() == buttonTypeOak) {
woodcuttingXP = woodcuttingXP + oakXP;
dialogue.appendText("You swing at an Oak tree. + " + oakXP + "XP.\n");
dialogue.appendText("You gathered 1 log.\n");
mainCharacter.getInventory().add(new OakLog());
}
Here is my Item Class:
package game;
public class Item {
private String name;
private int weight;
private int quantity;
private int value;
private String description;
public Item(String name, int value, String description) {
this.name = name;
this.value = value;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return getName();
}
}
And finally, here is my Character class:
package game;
import java.util.ArrayList;
import beverages.Water;
import items.OakLog;
import rawFood.Bread;
public class Character {
private String name;
private int hydrationLevel;
private int healthLevel;
private int hungerLevel;
private int woodcuttingLevel;
public int getWoodcuttingLevel() {
return woodcuttingLevel;
}
public void setWoodcuttingLevel(int woodcuttingLevel) {
this.woodcuttingLevel = woodcuttingLevel;
}
public int getHungerLevel() {
return hungerLevel;
}
public void setHungerLevel(int hungerLevel) {
this.hungerLevel = hungerLevel;
}
private ArrayList<Item> inventory = new ArrayList<Item>();
public ArrayList<Item> getInventory() {
return inventory;
}
public void setInventory(ArrayList<Item> inventory) {
this.inventory = inventory;
}
//creates a person with two basic items
public Character(String name){
this.name = name;
this.hydrationLevel = 100;
this.healthLevel = 100;
this.hungerLevel = 100;
this.woodcuttingLevel = 1;
addToInventory (new Bread());
addToInventory (new OakLog());
addToInventory (new Water());
}
//GETTERS AND SETTERS
public String getName() {
return name;
}
public int getHydrationLevel() {
return hydrationLevel;
}
public void setHydrationLevel(int hydrationLevel) {
this.hydrationLevel = hydrationLevel;
}
public int getHealthLevel() {
return healthLevel;
}
public void setHealthLevel(int healthLevel) {
this.healthLevel = healthLevel;
}
//END GETTERS AND SETTERS
/*Method Name: eat()
*Method Inputs: a piece of food
*Method Purpose: Will allow the user to eat food
*/
public Item getItemFromInventory(int index){
Item item = inventory.get(index);
return item;
}
public void addToInventory(Item item){
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
else{
item.setQuantity(1);
inventory.add(item);
}
}
public String toString(){
return "Character Stats:\nName:" + getName() + "\nHydration: " + getHydrationLevel() + "\nHealth: " + getHealthLevel() + "\nWoodcutting: " + getWoodcuttingLevel();
}
}
In your code, you have:
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
This just updates the quantity of the local variable item in the method, not the item in the inventory.
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.
I have two classes:
Products:
01; Desinfectante
02; Aerosol
03; Limpia Vidrio
04; Desengrasante
05; Mata mosquitos
06; Mata cucarachas
07; Aceite en aerosol
Instructions:
01;1;Elevar la masa hasta llegar a tal punto;0;10
01;1;Mezclar este material con anterior;1;15
01;2;Relevar;2;5
01;3;Llevar;00;0
02;1;Descripcion;7;2
02;2;Descripcion;6;2
02;2;Descripcion;00;0
03;1;Descripcion;1;1
03;1;Descripcion;2;9
03;2;Descripcion;00;0
03;3;Descripcion;5;2
03;4;Descripcion;6;2
03;4;Descripcion;3;10
04;1;Descripcion;00;0
04;2;Descripcion;1;2
04;3;Descripcion;1;0
04;3;Descripcion;2;2
04;3;Descripcion;3;2
04;4;Descripcion;7;1
04;4;Descripcion;6;2
05;1;Descripcion;7;20
05;1;Descripcion;6;9
05;2;Descripcion;00;0
05;3;Descripcion;1;2
05;3;Descripcion;2;10
06;1;Descripcion;2;12
06;1;Descripcion;4;1
06;1;Descripcion;6;8
06;2;Descripcion;5;4
06;2;Descripcion;7;2
07;1;Descripcion;1;12
07;1;Descripcion;2;2
07;2;Descripcion;3;19
07;2;Descripcion;4;4
07;2;Descripcion;00;2
07;2;Descripcion;5;12
The thing is this: i have to insert the instructions ArrayList into the Products. The link between them is the first number, that is the code of the product.
I tried two things, the first one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
products.get(i).getInstr().get(n).setCodProd(instructions.get(j).getCodProd());
products.get(i).getInstr().get(n).setDescr(instructions.get(j).getDescr());
products.get(i).getInstr().get(n).setMat(instructions.get(j).getMat());
products.get(i).getInstr().get(n).setMatNec(instructions.get(j).getMatNec());
n++;
}
}
n = 0;
}
The second one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).setInstr(instructions);
n++;
}
}
n = 0;
}
return products;
}
You are getting NullPointerException because of
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
You are not checking whether the list products.get(i).getInstr() has elements or not. When the list is empty and when you are accessing it as products.get(i).getInstr().get(0) it's throwing you NullPointerException because trying to get the first element of an empty list. So before you do this operation, make sure that products.get(i).getInstr() is not empty.
If they are of same type, you can directly add the whole arraylist :
products.get(i).getInstr().addAll(instructions); // again make sure that is not empty.
If you just want to replac, use :
products.get(i).setInstr(instructions.get(j));
Products Class
package productsandinstructions;
import java.util.List;
public class Product {
private int productId;
private String productName;
private List instructions;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
}
Instruction Class
package productsandinstructions;
public class Instruction {
private int productId;
private int instructionId;
private String instDesc;
private int mat;
private int matNec;
private boolean done;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getInstructionId() {
return instructionId;
}
public void setInstructionId(int instructionId) {
this.instructionId = instructionId;
}
public String getInstDesc() {
return instDesc;
}
public void setInstDesc(String instDesc) {
this.instDesc = instDesc;
}
public int getMat() {
return mat;
}
public void setMat(int mat) {
this.mat = mat;
}
public int getMatNec() {
return matNec;
}
public void setMatNec(int matNec) {
this.matNec = matNec;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
Main Class
package productsandinstructions;
import java.util.List;
public class ProductsAndInstructionsMain {
private List products;
private List instructions;
public List getProducts() {
return products;
}
public void setProducts(List products) {
this.products = products;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
public static void main(String[] args) {
ProductsAndInstructionsMain main = new ProductsAndInstructionsMain();
main.mergeProductsAndInstructions();
}
public void mergeProductsAndInstructions() {
for (Product product : products) {
for (Instruction instruction : instructions) {
if ((!(instruction.isDone())) && (instruction.getProductId() == product.getProductId())) {
product.getInstructions().add(instruction);
instruction.setDone(true);
}
}
}
}
}
I have a basket where products are added to and for each product there is a delete button:
Whenever I click the bottom button it deletes the bottom product, the problem is it also deletes the last item when clicked in the top button until the amount is 0 and the item is gone it deletes the 2nd one on the bottom (in this case the first item)
Here is my basket class code:
package model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Observable;
import main.WinkelApplication;
import view.Payment;
public class Basket extends Observable {
private final Map<Product, Integer> products;
public Basket() {
super();
products = new LinkedHashMap<Product, Integer>(); //Map zorgt ervoor dat keys??? aan values word gebonden (dit is een soort van variabele[i], i staat voor de key
}
public void addProduct(Product product) {
// check if product is allready added to the basket
if (products.containsKey(product)) {
products.put(product, products.get(product) + 1);
} else {
products.put(product, 1);
}
setChanged();
notifyObservers();
}
public void deleteProduct(Product product) {
// check if product is allready added to the basket
int i = WinkelApplication.getBasket().getProductAmount(product);
int id = product.getProductId();
if (WinkelApplication.getBasket().getProductAmount(product) == 1) {
products.remove(product);
WinkelApplication.getInstance().showPanel(new view.Payment());
}else{
i--;
products.put(product, i);
WinkelApplication.getInstance().showPanel(new view.Payment());
}
if (products.size() == 0) {
WinkelApplication.getInstance().showPanel(new view.CategoryList());
}
}
public void empty() {
products.clear();
setChanged();
notifyObservers();
}
public List<Product> getProducts() {
List<Product> list = new LinkedList<Product>(products.keySet());
return list;
}
public int getProductAmount(Product product) {
return products.get(product);
}
public int size() {
return products.size();
}
public double getTotalCosts() {
double total = 0.0;
for (Entry<Product, Integer> entry : products.entrySet()) { //gaat de lijst van producten af in basket, en doet de prijs bij totaal * het hoeveelheid van zo'n product
total += entry.getKey().getPrice() * entry.getValue();
}
return total;
}
}
As seen in the deleteProduct method I did products.remove(product) so I assume it then takes the last Item, if I System out the hash map it shows me: {Cars=2, Dames onderbroek=1} (according to the picture above). How can I make sure it deletes the selected one instead of the last one in the list?
The product class:
package model;
public class Product {
private int productId;
private int categorieId;
private String name;
private String description;
private double price;
public Product() {
this(-1, -1, "", "", 0.0);
}
public Product(int product_id, int categorie_id, String name, String description, double price) {
this.productId = product_id;
this.categorieId = categorie_id;
this.name = name;
this.description = description;
this.price = price;
}
/**
* #return the productId
*/
public int getProductId() {
return productId;
}
/**
* #param productId the productId to set
*/
public void setProductId(int productId) {
this.productId = productId;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the price
*/
public double getPrice() {
return price;
}
/**
* #param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* #return the categorieId
*/
public int getCategorieId() {
return categorieId;
}
/**
* #param categorieId the categorieId to set
*/
public void setCategorieId(int categorieId) {
this.categorieId = categorieId;
}
#Override
public String toString() {
return name;
}
#Override
public boolean equals(Object obj) {
boolean value;
if (obj instanceof Product) {
value = this.productId == ((Product)obj).productId; //VB: product1 (met ID 1) past deze methode toe, en geeft product2 als parameter: deze method geeft dan false terug.
} else {
value = super.equals(obj); //van wat is Product een subclass van? en wat heeft dit voor nut?
}
return value;
}
#Override
public int hashCode() { //wth is dit?
return 13 * 3 + this.productId;
}
}
Unfortunately you have not sent us the class Product but I can assume that you have not implemented hashCode() and equals() for this class.
The short answer - do this and your logic will work.
The longer answer is that hash mechanism uses these methods to identify your object. By default hashCode() returns the "address" in java heap, so 2 different instances of Product are different even if all their fields are equal. Pay attention that if equals() returns true hashCode() must return equal value for both objects.
WinkelApplication.getBasket() maybe delivers another basket?
Not an answer but one could get an error when the product is not in products.
public int getProductAmount(Product product) {
Integer i = products.get(product);
return i == null ? 0 : i.intValue();
}