如何正确调用 Item2.calculateUnitTotal() 以便我可以将金额添加到总变量

How to Correctly Call Item2.calculateUnitTotal() so I Can Add Amount to a Total Variable

好的!所以我对 Java 还是个新手,我们这周才开始学习实例和 classes。

我的问题是我的教授分配了一个程序(我已经花了大约 10 个小时,我已经取得了进展,但我仍然遇到问题)的说明有点模糊,我不是确定如何将它们合并到我的程序中。

这是一个购物车程序,可以获取产品的名称、描述、价格和数量。所有这些品质都进入 Item2 class,我没有遇到问题,然后使用 Item2 class 中的 toString() 方法打印.

接下来,我获取名称并将其添加到 ShoppingCart2 class(addItems 方法)中的数组,然后创建 getTotal 方法遍历 arrayItems,并将每个项目的价格相加(应该调用每个 Item 对象的 calculateUnitTotal() 方法并相加)。

我的问题是,通过尝试调用 calculateUnitTotal(),我得到了错误:

non static method cannot be referenced from a static context

或取消引用错误。

我的教授不希望我调用 Item2 class 中的单位和价格对象,我需要专门调用此方法。

我知道我需要创建一个实例来执行此操作,并且不能将对象转换为双精度对象,但我尝试的所有方法似乎都不起作用。

我不确定我做错了什么。我也知道代码有点乱,我尽力清理了。如有任何建议,我们将不胜感激!

Item2.java:


        class Item2{
            private String productName;
            public class Item2{
            private String productName;
            private String productDesc;
            private double unitPrice;
            private int units;

            public String getProductName(){
                return productName;
            }
            public String getproductDesc(){
                return productDesc;
            }
            public double getUnitPrice(){
                return unitPrice;
            }
            public int getUnits(){
                return units;
            }
            public void setProductName(String newProductName){
                productName = newProductName;
            }
            public void setProductDesc(String newProductDesc){
                productDesc = newProductDesc;
            }
            public void setUnitPrice(double newUnitPrice){
                unitPrice = newUnitPrice;
            }
            public void setUnits(int newUnits){
                units = newUnits;
            }

        void Item2(){
            productName = "";
            productDesc = "";
            unitPrice = -1;
            units = -1;} 

            public void Item2(String newProductName, String newProductDesc, 
            double newUnitPrice, int newUnits) {
                productName = newProductName;
                productDesc = newProductDesc;
                unitPrice = newUnitPrice;
                units = newUnits;
                }

           public double calculateUnitTotal(){
                double total = unitPrice * units;
                return total;
                }

          public String toStrings() {
               NumberFormat fmt = NumberFormat.getCurrencyInstance();
               return (productName + "\t" + fmt.format(unitPrice) + "\t" + 
               units + "\t" + fmt.format(unitPrice * units));
          }
       }

ShoppingCart2.java:

       class ShoppingCart2{
          private String[] arrayItems;
          private int numItems;

          public ShoppingCart2(){
              arrayItems = new String[20];
              numItems = 0;

          }
          public void addItems(String itemName){   
              for(int i = 0; i < numItems; i++){
                  if(numItems==arrayItems.length)
                     System.out.println("Cart is full.");
                  else{
                     arrayItems[numItems]= itemName;
                     numItems++;
                      }
                    }
                 }
         public ShoppingCart2 getTotal(){
              ShoppingCart2 total = new ShoppingCart2();

              for(int i = 0; i < numItems; i++){
               /////I've tried several different methods here, they always 
                 ////lead to either 
                 /// a need to dereference or the non static method error
               }
              return total;}

        public String toString() {
             NumberFormat fmt = NumberFormat.getCurrencyInstance();

             String cart = "\nShopping Cart\n";

             for (int i = 0; i < numItems; i++)
                  cart += arrayItems[i] + "\n";

                  cart += "\nTotal Price: " + fmt.format(total);
                  cart += "\n";

                  return cart;
             }
           }

我希望输出是数组中项目的名称和所有项目的总数。

听起来我的想法是使用Item2 class封装所有属性,然后使用ShoppingCart2来管理你用它们做什么。

因此,您的 ShoppingCart2 可能必须如下所示:

class ShoppingCart{
  private ArrayList<Item2> items;

  public ShoppingCart2(){
    items = new ArrayList<Item2>();
  }

  public void addItem(Item2 item){
    items.add(item);
  }

  public void addItems(ArrayList<Items> items){
    this.items.addAll(items)
  }

  public double getTotal(){
    double total = 0L;
    for(Item2 item : items){      
      total += item.calculateUnitTotal();
    }
    return total;
  }

  public String toString(){
     StringBuffer sb = new StringBuffer();
     for (Item2 item: items){
       // Print each item here
       sb.append(item.toString());
       sb.append("----------------\n");
     }
     sb.append("*************");
     sb.append("Total Price: ");
     sb.append(getTotal());
     return sb.toString();     
  }
}

注意:此代码未经过全面测试。

* 更新 *

仔细一看,你的Item2class是错误的。 这是一个更干净的版本。

class Item2 {
    private String productName;
    private String productDesc;
    private double unitPrice;
    private int units;

    public Item2(){
        productName = "";
        productDesc = "";
        unitPrice = -1;
        units = -1;
    } 

    public Item2(String newProductName, 
                String newProductDesc, 
                double newUnitPrice, 
                int newUnits) {
        productName = newProductName;
        productDesc = newProductDesc;
        unitPrice = newUnitPrice;
        units = newUnits;
    }

    public String getProductName(){
        return productName;
    }
    public String getproductDesc(){
        return productDesc;
    }
    public double getUnitPrice(){
        return unitPrice;
    }
    public int getUnits(){
        return units;
    }
    public void setProductName(String newProductName){
        productName = newProductName;
    }
    public void setProductDesc(String newProductDesc){
        productDesc = newProductDesc;
    }
    public void setUnitPrice(double newUnitPrice){
        unitPrice = newUnitPrice;
    }
    public void setUnits(int newUnits){
        units = newUnits;
    }

    public double calculateUnitTotal(){
        return unitPrice * (double) units;
    }

    public String toString() {
       NumberFormat fmt = NumberFormat.getCurrencyInstance();
       StringJoiner sj = new StringJoiner("\t");
       sj.add(productName).add(unitPrice).add(units).add(fmt.format(unitPrice * units));      
       return sj.toString();
    }   
}

一些解释

您希望在连接字符串时使用 StringJoiner 或 StringBuffer 的原因是它比使用加号 + 运算符更有效。

加号运算符产生大量开销,因为它需要两个参数,字符串,并从中创建一个全新的字符串。

StringBuffer 和 StringJoiner 允许您添加字符串,在最后一刻,您可以将它们一起变成一个字符串。