我需要从哪个方向完成购物车分配?

时间:2015-11-10 05:16:49

标签: java

所以我基本上完全迷失了我应该参加这项任务的地方。这就是作业要求我做的事情。

  

"第一部分:

     

设计一个名为Item的类,其中包含有关商店中待售商品的信息。项目具有以下属性:名称,供应商,价格,重量,应税(一个布尔字段,指示是否对项目征税)。

     

第二部分:

     

设计包含项目的ShoppingCart类。

有几种有趣的方法      

AddItem将项目插入购物车。   CartTotal计算购物车的总价。   CartTaxAmount收取税率并计算当前购物车中物品的总税费。此计算仅应考虑应税项目。

     

如果它更容易,你可以假设ShoppingClass的容量固定为10个项目。

     

请记住:

     

每个类至少应有一个接收参数的构造函数。   使数据成员私有,并在必要时创建访问器和更改器方法。

     

每个类都应该有一个toString方法,用于显示类的内容。   编写一个独立的函数,允许用户输入Item的信息并将Item返回给调用函数。   "

我只是不知道如何将类项目存储在另一个类的数组中。

import java.util.Scanner;
class Item {

//data members
private String Name;
private String Vendor;
private double Price;
private double Weight;
private boolean Taxable;

//constructor
Item(String conName, String conVendor, double conPrice, double conWeight, boolean Tax)
{
  Name = conName;
  Vendor = conVendor;
  Price = conPrice;
  Weight = conWeight;
  Taxable = Tax;
}

//Aceessor methods
public String getname(){
  return Name;
}

public String getvendor(){
  return Vendor;
}
public double getprice(){
  return Price;
}
public double getweight(){
  return Weight;
}
public boolean gettaxable(){
  return Taxable;
}

   public String toString()
  {
      String s = "Item Name is " + Name + " and the vendor is " + Vendor + ". The Price of the item is " + Price + " and the weight of the item is " + Weight + ". Item is taxable = " + Taxable + ".";
      return s; 
   }

   }


public class ShoppingCart {

   private Item[] itemsToBuy;
   private double taxRate;
   private int numItems;

   ShoppingCart(int capacity, double taxamount) {
      itemsToBuy = new Item[capacity];
      taxRate = taxamount;
      numItems = 0;
   }

   //Accessor methods

   public double gettaxRate(){
      return taxRate;
   }

   public int getItemNum() {
      return numItems;
   }
   public Item getitemsToBuy(int i) {
      return itemsToBuy[i];
   }

   //Methods

   public void AddItem() {



}

2 个答案:

答案 0 :(得分:1)

抬起头来;你走在正确的轨道上。您可以将项目传递给AddItem方法,然后将其插入itemsToBy数组中。您只需检查以确保购物车中有空间。

试试这个:

public void AddItem(Item item) {
    if(numItems < itemsToBuy.length){
        itemsToBuy[numItems] = item; //insert item in the array
        numItems++; //increment the number of items
    } else {
        System.out.println("Your cart is full.");
    }
}

为什么不尝试实施从购物车中删除最新商品的removeLastItem()方法。这应该可以帮助你练习。

我建议您在CaveofProgramming.com观看 Java for Complete Beginners 视频。当我第一次开始学习Java时,它们非常有用。

答案 1 :(得分:1)

我无法给你一个现成的答案,因为这显然是应该做的家庭作业。但是这里有一些指示可以帮助您更多地理解问题:

<强>物品

您需要创建一个名为Item的公共类。除了您可以进行的一些更改之外,这看起来与您已有的相似:

  1. 将类设为public(公共类Item)

  2. 你不需要像这样的大型构造函数。由于你有mutator方法,你可以保持构造函数的默认值,如下所示:

    public class Item {
        public Item() {
            // default constructor
        }
        ...
    }
    
  3. 更改您的getter / setter以使用每个私有成员xyz的getXyz和setXyz表单。注意大写的X,后跟小写的yz。

  4. 您不需要在toString()方法中打印语句;它会变长并且会用不必要的文本填满你的控制台。而是简单明了。另外,尝试使用StringBuilder构建字符串而不是使用字符串连接。虽然字符串连接不一定是坏的,但StringBuilder保持它不那么有争议:)

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getName()).append("\n")
          .append("\t name: ").append(getName()).append("\n")
          .append("\t vendor: ").append(getVendor()).append("\n");
        // do the same for all fields         
    
    
    return sb.toString();
    
    }
  5. <强>的购物

    您将需要一个名为ShoppingCart的公共类,它将包含Item对象列表;如下所示:

    <pre>
    import java.util.List;
    import java.util.ArrayList;
    
    public class ShoppingCart {
        private final List<Item> items; // items can be of any size
        private double taxRate;
    
        public ShoppingCart() {
            this.items = new ArrayList<Item>();
        }
    
        // getter for items List
        public List<Item> getItems() {
            return this.items;
        }
    
        // instead of a setter, we have an 'adder' which
        // adds one element. you can call this method
        // to add items one at a time to the items List
        public void addItem(Item item) {
            this.items.add(item);
        }
    
        // or you can use a varargs adder, using which
        // you have the convenience of adding more than
        // one item at a time
        public void addItem(Item... items) {
            if(items != null && items.length > 0) {
               for(Item item : items) {
                   this.items.add(item);
               }
            }
        }
    
        // getter for taxRate
        public double getTaxRate() {
            return this.taxRate;
        }
    
        // setter for taxRate
        public void setTaxRate(double taxRate) {
            this.taxRate = taxRate < 0 ? 0 : taxRate;
        }
    
        // item count is calculated; it's not a field getter
        public int getItemCount() {
            return this.items.size();
        }
    
        // calculates total price without taxes
        public double calculateCartPriceTotalNoTax() {
            double total = 0.0;
            for(Item item : this.items) {
               total += item.getPrice();
            }
    
            return total;
        }
    
        // calculates total price with taxes
        public double calculateCartPriceTotal() {
            double totalNoTax = calculateCartPriceTotalNoTax();
            double total = totalNoTax * getTaxRate() / 100;
    
            return total;
        }
    
        // calculates total price with taxes (different way of doing it)
        public double calculateCartPriceTotal2() {
            double total = 0.0;
            double taxRate = getTaxRate();
            for(Item item : this.items) {
               total += (item.getPrice() * getTaxRate() / 100);
            }
    
            return total;
        }
    
        // toString method for the ShoppingCart.
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append(getClass().getName()).append("\n")
              .append("\t items:             ").append(getItems()).append("\n")
              .append("\t taxRate:           ").append(getTaxRate()).append("\n")
              .append("\t totalPriceNoTax:   ").append(calculateCartPriceTotalNoTax()).append("\n")
              .append("\t totalPriceWithTax: ").append(calculateCartPriceTotal()).append("\n");
    
            return sb.toString();
        }
    }
    </pre>
    

    注意:

    可能您应该开始使用Eclipse(或IntelliJ Idea,如果您愿意)。它将使编写Java代码变得更加容易,并将帮助您避免许多错误。