属于同一类或继承类的包中的条目

时间:2018-08-13 20:44:36

标签: java

我无法完成《 Java的数据结构和抽象》一书中的源代码。

我已将Java文件包含在内。我的错误是在OnlineShopper.java中。

它说ArrayBag不存在,无法找到。

BagInterface<Item> shoppingCart = new ArrayBag<>();

有人知道我在想什么吗?非常感谢您阅读此问题。

来自 弗雷德

public interface BagInterface<T>
{
    public int getCurrentSize();

    public boolean isEmpty();

    public boolean add(T newEntry);

    public T remove();

    public boolean remove(T anEntry);

    public void clear();

    public int getFrequencyOf(T anEntry);

    public boolean contains(T anEntry);

    public T[] toArray();
}

    /** A class that maintains a shopping cart for an online store.
    @author Frank M. Carrano
    @version 4.0
    */
    public class OnlineShopper
    {
        public static void main(String[] args) 
        {
             Item[] items = {new Item("Bird feeder", 2050),
                  new Item("Squirrel guard", 1547),
                  new Item("Bird bath", 4499),
                  new Item("Sunflower seeds", 1295)};

             BagInterface<Item> shoppingCart = new ArrayBag<>();
             int totalCost = 0;

             // Statements that add selected items to the shopping cart:
             for (int index = 0; index < items.length; index++)
             {
                 Item nextItem = items[index]; // Simulate getting item from shopper
                 shoppingCart.add(nextItem);
                 totalCost = totalCost + nextItem.getPrice();  
             } // end for

             // Simulate checkout
             while (!shoppingCart.isEmpty())
             System.out.println(shoppingCart.remove());

             System.out.println("Total cost: " + "\t$" + totalCost / 100 + "." +
                     totalCost % 100);
         } // end main
      } // end OnlineShopper

物品类别:

public class Item
{
     private String description;
     private int    price;

     public Item(String productDescription, int productPrice) 
     {
         description = productDescription;
         price = productPrice;
     } // end constructor

     public String getDescription() 
     {
          return description;
     } // end getDescription

     public int getPrice() 
     {
         return price;
     } // end getPrice

     public String toString() 
     {
           return description + "\t$" + price / 100 + "." + price % 100;
     } // end toString
} // end Item

抱歉,点击错误

1 个答案:

答案 0 :(得分:0)

ArrayBag不是内置类,因此必须创建它。

从下面的代码行中,我们可以看到它必须实现BagInterface接口。

BagInterface<Item> shoppingCart = new ArrayBag<>();

接口及其实现均应使用泛型,因此代码应如下所示。

public class ArrayBag<T> implements BagInterface<T>{
   //Here you MUST implement all the methods declared in the interface.
   //Your IDE can help you with that.
}

您可以查看评论中提到的the tutorial about the genericsto this one about interfaces