这是我构建的第一个Java应用程序,我已成功为产品创建了一个类,但是现在我需要声明4个不同的产品实例,这样我就可以在代码的不同部分访问每个单独的产品。我现在的代码如下所示,但我似乎只能访问我创建的最后一个产品:
Products = new Products(1,2.50,"Coke",15);
Products = new Products(2,1.50,"Crisps",5);
Products = new Products(3,2.00,"Juice",2);
Products = new Products(4,2.50,"Chocolate",0);
System.out.println(Products.getProductID()+ " " + Products.getProductName());
有什么方法可以说'产品ID等于'或为每个产品实例分配一个名称? Appolagies如果在别处问过这个问题,我会查看相关帖子,但无法找到与Java相关的任何内容。 下面的代码显示了我的产品类:
public class Products {
private int ProductID;
private double ProductPrice;
private String ProductName;
private int ProductStock;
public Products(int ID, double Price,String PName,int Stock){
ProductID = ID;
ProductPrice = Price;
ProductName = PName;
ProductStock = Stock;
}
public void setProductID(int ID){
ProductID = ID;
}
public void setProductPrice(double Price){
ProductPrice = Price;
}
public void setProductName(String PName){
ProductName = PName;
}
public void setProductStock(int Stock){
ProductStock = Stock;
}
public int getProductID(){
return ProductID;
}
public double getProductPrice(){
return ProductPrice;
}
public String getProductName(){
return ProductName;
}
public int getProductStock(){
return ProductStock;
}
提前感谢您的帮助。
答案 0 :(得分:3)
如果不是(你没有显示变量名......)或者制作某种Collection(ArrayList,List等),你应该将变量命名为不同的。 例如
Products coke = new Products(1,2.50,"Coke",15);
Products crisps = new Products(2,1.50,"Crisps",5);
Products juice = new Products(3,2.00,"Juice",2);
Products chocolate = new Products(4,2.50,"Chocolate",0);
System.out.println(coke.getProductID()+ " " + juice.getProductName());
EG。 2
HashMap<Integer, Products> products = new HashMap<Integer, Products>();
products.put(products.size(), coke);
products.put(products.size(), crisps);
products.put(products.size(), juice);
products.put(products.size(), chocolate);
System.out.println(products.get(1).getProductID() + " " + products.get(1).getProductName());