简体   繁体   中英

Why my program is always throwing exception?

I am writing a Java program in which I need to check if a Product object is in the product list. If it is, I will call a private notify method and return a new ReceiptItem object. If it's not, I need to throw a ProductNotFound Exception. However, it seems like my program is always throwing ProductNotFound exceptions in any circumstances. Does anyone know what's the issue here?

public class StoreImpl implements Store {

  private final String name;
  private final List<StoreObserver> list;
  private final List<Product> product_list;
  private boolean flag;

  public StoreImpl(String name) {  \\Class constructor
    if (name == null) {
      throw new IllegalArgumentException("Invalid input");
    }
    this.name = name;
    list = new ArrayList<>();
    product_list = new ArrayList<>();
  }


public ReceiptItem purchaseProduct(Product product) { 
    flag = false;
    if (product == null) {
      throw new IllegalArgumentException("Invalid input");
    }
    for (Product pros : product_list) {
      if (pros == product) {
        flag = true;
      }
    }
    if (flag == false) {
      throw new ProductNotFoundException("Product not found");
    } else {
      if (((ProductImpl) product).getInventory() == 0) {
        notify(new OutOfStockEvent(product, this));
      }
      notify(new PurchaseEvent(product, this));
      return new ReceiptItemImpl(product.getName(), product.getBasePrice(), name);
    }
  }

  
  }

Override equals method in Product class to compare 2 objects check following sample.

class Product{
    .....
    // Other functions
    .....
    public boolean equals(Product p2)
    {
         if(this.attrib1 == p2.attrib1)
         {
            if(this.attrib2 == p2.attrib2)
            {
                 // Like this compare all attributes
                 return true;
            }
            else
                 return false;
         }
         else
              return false;
    }
}

After this use this method wherever you want to compare 2 objects.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM