[英]How to search in arrayList then change?
所以我正在制作一個允許添加產品並銷售它們的超市程序,到目前為止我有這個:
class Product
{
String name;
double price;
int day;
int month;
int year;
int stock;
public Product(String name,double price,int day,int month,int year,int stock)
{
this.name=name;
this.price=price;
this.day=day;
this.month=month;
this.year=year;
this.stock=stock;
}
}
class SuperMarket{
protected String name;
protected int numMax;
private List<Product> pr;
public SuperMarket(String name,int numMax)
{
this.name=name;
this.numMax=numMax;
this.pr = new ArrayList<Product>();
}
public void addProduct() {
//deleted to post here
}
public void sellProduct()//its here i need help
{
Scanner sc=new Scanner(System.in);
System.out.println("What product do you want to sell?");
String name=sc.nextLine();
}
}
我想知道如何按名稱在產品列表中搜索,然后更改庫存(減去 n)以銷售該產品的 n。
您可以使用 Stream API 按名稱查找產品。 通過檢查產品名稱過濾列表並獲得第一個匹配項。
Optional<Product> product = productList.stream()
.filter(e -> e.name.equals(inputedName))
.findFirst();
然后可以檢查是否找到產品然后更新庫存
if(product.isPresent()){
Product p = product.get();
p.stock = p.stock - numberOfSoldProduct;
}
建議對字段使用 getter/setter。
如果您希望使用 O(1) 進行搜索,則可以使用 map。 但是我認為沒有必要列出清單。
public SuperMarket(String storeName,int storeId){
this.storeName = storeName;
this.storeId = storeId;
this.products = new ArrayList<Product>();
this.productByName = new HashMap<String, Product>();
}
public void addProduct(Product product) {
String productName = product.name;
if(productByName.containsKey(productName)){
Product existingProduct = productByName.get(productName);
existingProduct.stock += product.stock;
existingProduct.price = product.price;
}else{
productByName.put(productName, product);
products.add(product);
}
}
public void sellProduct(String productName, int count){
if(!productByName.containsKey(productName)){
System.out.println(productName + " is unavailable !!!");
return;
}
Product existingProduct = productByName.get(productName);
existingProduct.stock -= count;
if(existingProduct.stock <= 0){
productByName.remove(productName);
products.remove(existingProduct);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.