我正在尝试为鞋子实施库存计划。我想要做的是给每只鞋子一个id(productId)和一定数量的鞋子(ammountToPick)。我希望能够让运行程序的用户输入鞋子ID以获得剩余库存的那种鞋子的数量(ammountToPick)。我当前的程序问题是它没有返回任何东西,只是继续打印“无效的产品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 ");
}
}
}
答案 0 :(得分:1)
if(userinput.equals(productId)) {
System.out.println("there are" + product[1].getAmmountToPick() +"left");
}
else {
在第一行,问题是productId设置为类顶部的空字符串。如果你只是按Enter键而不输入实际的productId并且userinput是""它实际上应该工作。但要以您想要的方式工作,请删除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");
}
}
答案 1 :(得分:0)
Product
和Inventory
类都有productId
个成员变量。您将userInput
与private static
类中的productId
Inventory
进行了比较,这是一个空字符串。
我认为您应该遍历您的广告资源数组,寻找与productId
的{{1}}匹配的内容。
这是使用增强型循环并且没有新方法的一种方法:
Product
我将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
。它应该被删除。