Java相关,包括使用构造函数和类

时间:2014-08-21 01:18:20

标签: java

我正在自学AP计算机科学,我对这个问题有点麻烦。

  1. 组织通过销售饼干来筹集资金。 cookie订单指定cookie的种类和订购的盒子数量。 CookieOrder类的声明如下所示。

    public class CookieOrder
    {
    /**
    Constructs a new
    CookieOrder
    object.
    */
    public CookieOrder(String variety, int numBoxes)
    { /*
    implementation not shown
    */ }
    /** @return
    the variety of cookie being ordered
    */
    public String getVariety()
    { /*
    implementation not shown
    */ }
    /** @return
    the number of boxes being ordered
    */
    public int getNumBoxes()
    { /*
    implementation not shown
    */ }
    // There may be instance variables, constr uctors, and methods that are not shown.
    } 
    
  2. MasterOrder类维护要购买的cookie列表。 MasterOrder类的声明如下所示。

    public class MasterOrder
    {
    /**
    The list of all cookie orders
    */
    private List<CookieOrder> orders;
    /**
    Constructs a new
    MasterOrder
    object.
    */
    public MasterOrder()
    { orders = new ArrayList<CookieOrder>(); }
    /**
    Adds
    theOrder
    to the master order.
    * @param theOrder
    the cookie order to add to the master order
    */
    public void addOrder(CookieOrder theOrder)
    { orders.add(theOrder); }
    /** @return
    the sum of the number of boxes of all of the cookie orders
    */
    public int getTotalBoxes()
    { /*
    to be implemented in part (a)
    */ }
    /**
    Removes all cookie orders from the master
    order that have the same variety of
    *
    cookie as
    cookieVar
    and returns the total number of
    boxes that were removed.
    * @param cookieVar
    the variety of cookies to remove from the master order
    * @return
    the total number of boxes of
    cookieVar
    in the cookie orders removed
    */
    public int removeVariety(String cookieVar)
    { /*
    to be implemented in part (b)
    */ }
    //
    There may be instance variables, constr
    uctors, and methods that are not shown.
    }
    

    (a)getTotalBoxes方法计算并返回所有cookie订单的框数之和。如果主订单中没有cookie订单,则该方法返回0.完整方法getTotalBoxes如下。

    /** @return
    the sum of the number of boxes of all of the cookie orders
    */
    public int getTotalBoxes() 
    
    According to college board the answer is:
    
    int sum = 0;
    
    for (CookieOrder a: this.orders)
        sum += a.getNumBoxes();
    
    return sum;
    

    以下是我的问题:

    1. “CookieOrder”是一种类型?

    2. 如果我打印出'a',会打印出什么?

    3. 为什么需要关键字“this”?

    4. 我更喜欢一个对大脑友好的答案。

1 个答案:

答案 0 :(得分:2)

  

1。 “CookieOrder”是一种类型?

这是一种类型,因为它是defined in a class declaration.

  

2。如果我打印出'a',会打印出什么?

为什么这是一个假设?运行代码并查看。

  

3.为什么需要关键字“this”?

在这种情况下不需要但是,有些人可能会认为它可以改善代码风格/维护/可读性/在这种情况下的任何内容。