Reputation: 31
I need to create a SETTER method within Class B to set a new price for particular Product object which is stored in array defined in Class A. Can anyone help with this basic java code? Let's assume that we create Product apple and we need to change its price. I need to use something like:
setPrice (product name, price);
Here is scenario:
Class A
public class Store(){
Store(Product aProduct){
products = new ArrayList< Product> ();
}
}
Class B
private String name;
private int price;
public class Product {
Product ( String aName, int aPrice) {
name = aName;
price = aPrice;
}
}
Thanks very much.
Upvotes: 2
Views: 551
Reputation: 55
There is a lot more that needs to be implemented for this to be a working solution. Here are some of the things that you will need to do:
Class A:
Class B:
Setter:
public void setPrice(int _price){
this.price = _price;
}
Getter:
public String getName(){
return this.name;
}
One thing to consider in addition, would your price not want to be of type double? int doesn't allow for decimal places.
Upvotes: 1
Reputation: 2433
public class Store(){
List<Product> products;
Store(){
products = new ArrayList<Product>();
}
public addProduct(product){
products.add(product)
}
public boolean setPrice(String productName,int price){
for(Product product: products){
if(product.name.equalsIgnoreCase(productName) ){
product.price = price;
return true;
}
}
return false;
}
}
public class Product {
private String name;
private int price;
Product (String aName, int aPrice) {
this.name = aName;
this.price = aPrice;
}
}
Hope this helps
Upvotes: 1