Dylan
Dylan

Reputation: 454

Updating the value of an object in an arraylist

This problem has been bugging me for the last while.. i cant seem to be able to update the stock value of the vehicle that i'm selling. I understand how to search the array and locate the model that the user is looking for but i don't understand how to update the number of that specific model vehicle that are in stock. which is going to be stock - 1 after a purchase.

I have both basic getters and setters for model and stock variables in the Vehicles superclass

Any help is appreciate!

Below is the method of purchasing a car from the driver class

     public void purchaseCar()
{
    Scanner scan = new Scanner(System.in);
    String model, ans;
    System.out.println("****Car Purchase Page****");
    System.out.println("Enter the model of car you're looking to purchase");
    model = scan.nextLine();
    for (Vehicles v : list) {
        if (v.getmodel().equals(model))
        {
            System.out.println("Is this the model you want to purchase?");
            ans = scan.nextLine();
            if (ans.equals("yes")) {
                System.out.println("Okay! Your order is being processed");
                Vehicles.setStock() = stock - 1;
                    }
                else { 
                    System.out.println("not working");

                }
            }
        }
    }

Upvotes: 0

Views: 93

Answers (2)

Guillaume Barré
Guillaume Barré

Reputation: 4228

You are not invoking the Vehicles.setStock() on the object you want to update. And in addition this method doesn't receive any parameter to update the new stock.

You should call the method on the instance you want to update passing it the new value of the stock.

Try this

v.setStock(v.getStock() - 1);

If it seems strange to you to use the v.getStock() to build the parameter you can create a new method within your vehicle class.

class Vehicles{
    int stock;

    public void consumeOne(){
        stock = stock -1;
    }
}

And then you can call this new method in the for statement

for (Vehicles v : list) {
    if (v.getmodel().equals(model)){
        ans = scan.nextLine();
        if (ans.equals("yes")) {
            v.consumeOne();
        }else { 
            System.out.println("not working");
        }
    }
}

Upvotes: 0

Jorn Vernee
Jorn Vernee

Reputation: 33905

You're almost there.

Change:

Vehicles.setStock() = stock - 1;

to:

v.setStock(v.getStock() - 1);

As clarification, this is the same as:

int stock = v.getStock(); // Get the current stock value of 'v'
int newStock = stock - 1; // The new stock value after the purchase
v.setStock(newStock);     // Set the new stock value

Upvotes: 2

Related Questions