在 Java 中实施 Shoe Inventory 程序时遇到问题

Trouble implementing Shoe Inventory program in Java

我正在尝试实施一个鞋子库存计划。我想做的是给每只鞋一个 ID (productId) 和一个库存鞋的数量 (ammountToPick)。我希望能够要求用户 运行 程序输入鞋子 ID 以获取库存中剩余的该类型鞋子的数量 (ammountToPick)。我的程序目前的问题是它没有返回任何东西,只是一直打印 "invalid product id"。

我在下面提供了我的代码:

public class Product {
  private String productId = "";
  private int ammountToPick = 0;
  private int ammountToRestock = 0;

  public Product (String productId, int ammountToPick){

   this.productId = productId;
   this.ammountToPick = ammountToPick;

  }

  public String getProductId() {
    return productId;
  }

  public int getAmmountToPick() {
    return ammountToPick;
  }

}

public class Shoes extends Product{
  public Shoes(String productId, int ammountToPick){
   super(productId, ammountToPick); 

  }


}

import java.util.Scanner;  
public class Inventory
{
    private static String productId = "";
  private int ammountToPick = 0;
  private int ammountToRestock = 0;
  public static final int MAX_ITEMS = 999999;
  private static Product product [] = new Shoes[MAX_ITEMS];

  public static void main (String args[]){

  buildInventory();
  getInventory();
}

public static void buildInventory(){

product[1] = new Shoes("shoe101", 19);
product[2] = new Shoes("shoe200", 1);
product[3] = new Shoes("shoe420", 9);
}

public static void getInventory() {
  Scanner input = new Scanner(System.in);
  System.out.println("Enter the product id of the product you would like to pick: ");
  String userinput = input.nextLine();
  if(userinput.equals(productId)) {
    System.out.println("there are" + product[1].getAmmountToPick() +"left");
  }
  else {

   System.out.println("invalid product id ");
  }
}
}
if(userinput.equals(productId)) {
    System.out.println("there are" + product[1].getAmmountToPick() +"left");
  }
else {

在第一行,您的问题是 productId 在 class 的顶部设置为空字符串。如果您只是按回车键而不输入实际的 productId 并且用户输入是“”,它应该可以正常工作。但是要按照您想要的方式进行这项工作,请删除您的 productId 变量并检查 userinput 是否与数组中的一项的 productId 匹配

你需要做的

userinput = ...; //this part is fine
for (Product p : products) {
  if (userinput.equals(p.getProductId())) {
    System.out.println('there are ' + p.getAmmountToPick() + " left");
  }
}

ProductInventory class 都有 productId 成员变量。您正在将 userInputInventory class 中的 private static productId 进行比较,这是一个空字符串。

我认为您应该遍历清单数组以查找与 ProductproductId 匹配的项。

这是一种使用增强循环且没有新方法的方法:

boolean found = false;
for (final Product aProduct: product) {
    if(userInput.equals(aProduct.getProductId())) {
        System.out.println("there are" + aProduct.getAmmountToPick() +"left");
        found = true;
        break;
    }
}
if(!found) {
    System.out.println("invalid product id ");
}

我将 product 成员变量重命名为 products,这样它的意图就更清楚了。它也会使上面的代码更清晰。

Inventory,按照您的使用方式,不需要 productId。应该删除。