B Patton
B Patton

Reputation: 31

Java, setter method for array. Two classes

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

Answers (2)

Dan Kerby
Dan Kerby

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:

  • Declare products variable
  • Create method for finding a product (foreach loop, compare product name to the method parameter, use product Getter for name, return Product object)
  • Create a method for setting the price, parameters of price and name. Uses setter method from Class B
  • Remove Product object from constructor parameters
  • Add method for adding a product to the ArrayList (Create new Product object, add to ArrayList)

Class B:

  • Add Setter method for price (see below)
  • Add Setter method for name
  • Add Getter method for price
  • Add getter method for name (see below)

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

JohnTheBeloved
JohnTheBeloved

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

Related Questions