这个问题最近一直困扰着我。我似乎无法更新我正在销售的车辆的库存值(value)。我了解如何搜索数组并找到用户正在寻找的型号,但我不了解如何更新库存的特定型号车辆的数量。购买后将有库存 - 1。
我在车辆父类(super class)中拥有模型和库存变量的基本 getter 和 setter
非常感谢您的帮助!
下面是从司机阶层购买汽车的方法
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");
}
}
}
}
最佳答案
你就快到了。
更改:
Vehicles.setStock() = stock - 1;
至:
v.setStock(v.getStock() - 1);
<小时/>
澄清一下,这与:
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
关于java - 更新数组列表中对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36985520/