I am trying to implement an Inventory program for shoes. What I am trying to do is give each shoe an id (productId) and a quantity of shoes that are in stock (ammountToPick). I want to be able to ask the user running the program to enter a shoe id to get the amount of that type of shoe that are left in stock (ammountToPick). My current problem with my program is that it is not returning anything and just keeps printing "invalid product id".
I have provided my code below:
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 {
On the first line, you problem is that productId is set to an empty string at the top of the class. It should actually work if you just hit enter without entering an actual productId and userinput is "". But to make this work the way you want, get rid of your productId variable and check if userinput matches a productId of one of the items in your array
you need to do
userinput = ...; //this part is fine
for (Product p : products) {
if (userinput.equals(p.getProductId())) {
System.out.println('there are ' + p.getAmmountToPick() + " left");
}
}