I am writing an addition to a java inventory problem that uses an arraylist to write methods to add, search for, etc. items in an inventory.
I am using another class called InventoryItem which has variables for sku, itemName, price, and stock.
I would like to know if I am on the right track in using a perviously defined class in writing a method to add an item.
import java.util.*;
public class Warehouse {
private ArrayList<InventoryItem> inventory = new ArrayList<InventoryItem>();
public static void addItem(InventoryItem i )
inventory.add(i);
}
public static void main(String [] args) {
addItem();
}
}
This is the InventoryItem class;
public class InventoryItem {
private int sku;
private String itemName;
private double price;
private int stock;
public InventoryItem (int sku, String itemName, double price, int stock) {
this.sku = sku;
this.itemName = itemName;
this.price = price;
this.stock = stock;
}
public int getSku() {
return sku;
}
public String getitemName () {
return itemName;
}
public void setPrice (double price) {
this.price = price;
}
public double getPrice () {
return price;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getStock() {
return stock;
}
#Override
public String toString() {
return String.format("[%d ,%s ,%1.2f ,%d]", sku, itemName, price, stock);
}
public static void main(String[] args) {
InventoryItem itemName = new InventoryItem(1, "asdf", 2.4, 5);
System.out.println(itemName);
}
}
The major problem with your addItem() method is that it is static, so it won't be able to access the warehouse list, which is an instance variable that can only be accessed from an instance.
To fix this (and other) problems, try this:
public class Warehouse {
private List<InventoryItem> inventory = new ArrayList<InventoryItem>();
public void addItem(InventoryItem i)
inventory.add(i);
}
public static void main(String [] args) {
// create a Warehouse instance
Warehouse warehouse = new Warehouse();
// create an InventoryItem instance
InventoryItem i = new InventoryItem(sku, itemName, price, stock);
// add the InventoryItem to the Warehouse
warehouse.addItem(i);
}
}
You are on the right lines. When you call the addItem() method, you will need to pass in an InventoryItem object. So perhaps something more like:
double sku = 111;
String itemName = "someItem";
double price = 2.99;
int stock = 1;
InventoryItem inventoryItem = new InventoryItem(sku, itemName, price, stock);
addItem(inventoryItem);
You will of course need to make sure you have a constructor in your InventoryItem class which takes in the params that you need.
So, based on your InventoryItem class, and the extra tips from Bohemian below it would look like this:
import java.util.ArrayList;
import java.util.List;
public class Warehouse {
private List<InventoryItem> inventory = new ArrayList<InventoryItem>();
public void addItem(InventoryItem i) {
inventory.add(i);
}
public static void main(String [] args) {
// create a Warehouse instance
Warehouse warehouse = new Warehouse();
// create an InventoryItem instance
int sku = 111;
String itemName = "someItem";
double price = 2.99;
int stock = 1;
InventoryItem i = new InventoryItem(sku, itemName, price, stock);
// add the InventoryItem to the Warehouse
warehouse.addItem(i);
}
}
Related
So I have 4 classes, Testest which has a main method, Phone which extends Product, Product and ProductDB which has a hashmap. When I make a new phone I want the phone to be stored in the database automatically.
public class Product {
protected String productID;
protected String name;
private String description;
private double price;
public Product(){
Product db = new ProductDB();
productID = this.toString();
db.add(productID, this);
}
(Getter and setter methods here...)
}
public class Phone extends Product {
private String make;
private String model;
private int storage;
public Phone(String make, String model, int storage){
this.make = make;
this.model = model;
this.storage = storage;
}
(Getter and setter methods here...)
}
import java.util.HashMap;
public class ProductDB {
private HashMap<String,Product> products = new HashMap<String, Product>();
public void add(String productID, Product product){
products.put(productID, product);
}
public void remove(String productID){
products.remove(productID);
}
public Product find(String productID){
return products.get(productID);
}
public Object showAll(){
return products.values().toArray();
}
}
public class Testest{
public static void main(String[] args){
ProductDB db = new ProductDB();
Phone phone1 = new Phone("Huwawei P30", "HP30", 50000);
Phone phone2 = new Phone("Huwawei P30 Pro", "HP30PRO", 70000);
Phone phone3 = new Phone("Samsung Galaxy SX", "SGSX", 65000);
System.out.println(db.find(phone1.productID));
System.out.println(phone1.productID);
}
}
I want this to return the object when I look for that specific id, but the problem is that the HashMap is empty for some reason
Edit I made productID private. Still nothing
It seems you want your database to include all created phones, in this case instead of creating a database each time which will be useless and also because your database is accessed from several places it will be more consistent to make your database fields and methods static and just access it from where you want:
public class ProductDB {
final private static HashMap<String,Product> products = new HashMap<String, Product>();
public static void add(String productID, Product product){
products.put(productID, product);
}
public static void remove(String productID){
products.remove(productID);
}
public static Product find(String productID){
return products.get(productID);
}
public static Object showAll(){
return products.values().toArray();
}
}
And then in Product constructor just write:
public Product{
productID = this.toString();
ProductDB.add(productID, this);
}
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 am working on my class assignment and I am stuck.
I have two classes: Part, which is abstract and has InHouse and Outsourced classes that extend Part. Then I have Product, which oddly has an observableArrayList of parts called associatedParts.
I am working on my AddProductController, trying to make a call to the method in the Product class addAssociatedPart(). My problem is the compiler doesn't find the method in Part. If I cast to an InHouse, it doesn't find the method in InHouse, and so on. I can't use a static method, because the method addAssociatedPart() is supposed to be non-static per the UML design. So, I can't tell it explicitly to find it in Product.addAssociatedPart(), because it tells me I can't reference a non-static etc.
Here's the code snippets starting with the Product class.
public class Product {
private ObservableList<Part> associatedParts = FXCollections.observableArrayList();
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
public void addAssociatedPart(Part part) {
getAllAssociatedParts().add(part);
}
public ObservableList<Part> getAllAssociatedParts() {
return this.associatedParts;
}
And then the AddProductScreenController class:
public class AddProductScreenController implements Initializable {
#FXML
public void onAddProductAddPart(ActionEvent event) {
// this is triggered when the Add button is clicked
Part selectedItem = addProductTableViewAll.getSelectionModel().getSelectedItem();
selectedItem.addAssociatedPart(); // can't find method
Product.selectedItem.addAssociatedPart(); // can't find variable selectedItem (obviously bad formatting)
selectedItem.Product.addAssociatedPart(); // can't find variable Product (again bad formatting)
addAssociatedPart(selectedItem); // can't find method addAssociatedPart()
Product.addAssociatedPart(selectedItem); // non-static method, can't be referenced from a static context
InHouse newPart = new InHouse(1, "test", 1.99, 1, 1, 1, 101);
addAssociatedPart(newPart); // can't find method
Product.addAssociatedPart(newPart); // non-static method
newPart.addAssociatedPart(); // can't find method
addProductTableViewPartial.setItems(associatedParts);
}
}
The part code as requested:
public abstract class Part {
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
public ObservableList<Part> allParts = FXCollections.observableArrayList();
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 void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getStock() {
return this.stock;
}
public void setMin(int min) {
this.min = min;
}
public int getMin() {
return this.min;
}
public void setMax(int max) {
this.max = max;
}
public int getMax() {
return this.max;
}
}
This is InHouse
package model;
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 void setMachineId(int machineId) {
this.machineId = machineId;
}
public int getMachineId() {
return this.machineId;
}
}
And then Outsourced:
package model;
public class Outsourced extends Part {
private String companyName;
public Outsourced(int id, String name, double price, int stock, int min, int max, String companyName) {
super(id, name, price, stock, min, max);
this.companyName = companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyName() {
return this.companyName;
}
}
If there is a particular part of Java you feel I need to brush up on to understand this, I am wide open to that. I want to understand the issue, not just get a fix. I'm not even looking for the answer, just a point in the direction of what the problem is.
Update
#Le and #Jackson pointed me in the right direction with their comments on the response he provided. I need to have a product first:
Product product = new Product(1, "test", 1.99, 1, 1, 1);
product.addAssociatedPart(selectedItem);
I was trying to explain you association of your various classes in comments but thought I would use visual help. I have simplified your scenario into a classic OOP problem.
public class Product {
public void addAssociatedPart(Part part) {
// some stuff
}
}
public abstract class Part {
}
public class InHouse extends Part {
}
public class Outsourced extends Part {
}
public class Assembly {
public static void main(String[] args) {
Product car = new Product();
Part seat = new InHouse();
Part engine = new Outsourced();
Part window = new InHouse();
car.addAssociatedPart(seat);
car.addAssociatedPart(engine);
car.addAssociatedPart(window);
}
}
I do not have any method in my Part or its sub-classes to add themselves to some Product. Was this you trying to achieve?
I am working on my AddProductController, trying to make a call to the
method in the Product class addAssociatedPart().
My problem is the compiler doesn't find the method in Part.
Why should it? Is Part a child of Product? Otherwise, you are calling a Product Method using a Part instance.
To use the methods of Inhouse and Oursourced for parts, you can do something like this
if (selectedItem instanceof InHouse){
Inhouse inhouse = (Inhouse)selectedItem;
//do what you need with inhouse methods
}else{
Outsourced outsourced = (Outsourced)selectedItem;
//do what you need with oursourced method
}
You are confused with static and non static method. You need a Product instance to access AddAssociatedPart(). Visualize your class in class diagram.
public void onAddProductAddPart(ActionEvent event) {
// this is triggered when the Add button is clicked
Part selectedItem = addProductTableViewAll.getSelectionModel().getSelectedItem();
selectedItem.addAssociatedPart(); // addAssociatedPart() is method of Product, not Part
Product.selectedItem.addAssociatedPart(); // Product class has no static member selectedItem
selectedItem.Product.addAssociatedPart(); // syntax error
addAssociatedPart(selectedItem); // addAssociatedPart() is not method of AddProcutController
Product.addAssociatedPart(selectedItem); // if you reference the method start with a class, the method is expected to be a static method. addAssociatedPart() is not a static method, call it with a product instance
InHouse newPart = new InHouse(1, "test", 1.99, 1, 1, 1, 101);
addAssociatedPart(newPart); // addAssociatedPart() is not part of AddProductController
Product.addAssociatedPart(newPart); // dont reference non-static method with a class name
newPart.addAssociatedPart(); // addAssociatedPart() is not part of Part
addProductTableViewPartial.setItems(associatedParts);
}
I have a question about hashmap,
I have a class product:
public class product{
private String libele;
and also a class special product:
public class SpecialProd extends Product{
private HashMap<Product, Price> comp = new HashMap<Product, Price>();
public HashMap<Product, Price> getComp() {
return comp;
}
}
The problem is that i need to know how much products i have in stock, the total amount of the products and how much for every product:
so i used this code in the class storage:
public class Storage{
private HashMap<Product, Price> port = new HashMap<Product, Price>();
public void total (){
int nombre=0;
int total = 0;
int i=0;
for (Product p:port.keySet()){
if (port.containsKey(a)){
// ++nombre;
}
total = port.size();
System.out.println(+nombre+ "of" +a.getLibele());
}
System.out.println("total products:" +total);
}
// this is an intern class
static class Part{
private int price;
public Price(int price) {
this.price= price;
}
public int getprice() {
return price;
}
public void setPrice(int price) {
this.price= price;
}
}
}
i couldn't get the count of every product and the total prices.
Any ideas please?
You can try enumerating the HashMap and get the desired values.
int count=0;
for(p : port.keySet()){
count ++;
price = price + port.get(a);
}
when i trying to do this i got the problem said
Constructor Product in class Product cannot be applied to given types;
required: java.lang.String,int,double; found: java.lang.String;
reason: actual and formal arguments lists differ in length
And i have 2 classes:
import java.text.*
public class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
new Store().use();
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
public void use() {
}
private void sell() {
}
private void restock() {
}
private void viewStock() {
}
private void viewCash() {
}
private void help() {
System.out.println("Menu options");
System.out.println("s = sell");
System.out.println("r = restock");
System.out.println("v = view stock");
System.out.println("c = view cash");
System.out.println("x = exit");
}
}
I understand that i have to declare for Product constructor. But i think i have done it. If anyone know where i got wrong please explain. Thank you!
you do not have constructor with one param, so you can not using this form
product = new Product("Sticky tape");
decare one more constructor with one param or fill all param
product = new Product("Sticky tape", 10, 20.0);
You need to:
overload the constructor
public Product(String name){...}
or create instances of Product using the right and only one constructor uor have:
public Product(String name, int stock, double price)
if you overload then something like this should happen
public Product(String name){
this(name, 0, 0.0);
}
so you call a constructor from the other constructor
This is the time to learn constructor overloading. Overloading comes from OOP.
You can use Overloading to methods and constructors. Overloading means for a same method name you can implement that method
several time with different parameters(number of parameters)
. Actualy not only that,
you can use different data types for parameter.
also can change order of parameter.
keep remember method name must be same.
For the constructor also same thing. If you use for constructor you can add parameters like:
//constructor with one parameter
public Product(String name) {
this.name = name;
this.stock = 0;//or whatever your default value
this.price = 0;//or whatever your default value
}
//constructor with two parameter
public Product(String name, , int stock) {
this.name = name;
this.stock = stock;
this.price = 0;//or whatever your default value
}
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
Like that you can add as many as you want.
Or you can use one constructor and pass argument to match with the implementation of the constructor when creating object. Like below:
product = new Product("Sticky tape", 0, 0);
this is not complete description you can read this to learn more
You have no constructor In Product class that takes single String argument. Create it like so:
public Product(String name) {
this.name = name;
}
In import statement you forgot semicolon:
import java.text.*;
your program is having 3 coding error which include
you forgot the " ; " after " import java.text.* " actually it is not required in your code, you can remove it, nothing will change.
you cannot make class Product as public , because you've made "Store" as your Primary class having main method.So remove public keyword from the Product class.
You didn't create a parameterized constructor
which should be like
public Product(String name){ this.name = name;}
in your product class.
your code will be like after correcting
class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public Product(String name) {
this.name = name;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
Store s = new Store();
System.out.println(s.product);
System.out.println(s.cashRegister);
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
}
The errors are in these lines of code:
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
The Product constructor defined expects:
public Product(String name, int stock, double price)