So i'm making a supermarket program that allows to add products and sell them, so far i have this:
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();
}
}
I´d like to know how to search in Product list by name and then change the stock(subtract-n) to sell n of that product.
You can use Stream API to find out the product by name. Filter the list by checking the name of product and get first match.
Optional<Product> product = productList.stream()
.filter(e -> e.name.equals(inputedName))
.findFirst();
Then can check is product found then update the stock
if(product.isPresent()){
Product p = product.get();
p.stock = p.stock - numberOfSoldProduct;
}
Suggestion to use getter/setter for fields.
In case if you are looking to get search using O(1), you can use map. however i don't see necessary of list though.
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);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.