迭代器和打印细节

时间:2010-11-30 12:28:02

标签: java

嘿所有人。我被要求创建一个使用迭代器打印'lot'细节的方法。我能够创建一个打印所有细节的迭代器,但是,对于任何尚未购买的批次,消息应该打印出这个事实,我不确定如何添加该代码。它是public void close method我正专注于。这就是我到目前为止所拥有的。非常感谢帮助。

public class Auction{

    // The list of Lots in this auction.
    private final ArrayList<Lot> lots;
    // The number that will be given to the next lot entered
    // into this auction.
    private int nextLotNumber;

    /**
     * Create a new auction.
     */
    public Auction(){
        lots = new ArrayList<Lot>();
        nextLotNumber = 1;
    }

    /**
     * Enter a new lot into the auction.
     * 
     * @param description
     *            A description of the lot.
     */
    public void enterLot(final String description){
        lots.add(new Lot(nextLotNumber, description));
        nextLotNumber++;
    }

    /**
     * Show the full list of lots in this auction.
     */
    public void showLots(){
        for(final Lot lot : lots){
            System.out.println(lot.toString());
        }
    }

    public void close(){
        final Iterator<Lot> it = lots.iterator();
        while(it.hasNext()){

        }
    }

    /**
     * Bid for a lot. A message indicating whether the bid is
     * successful or not is printed.
     * 
     * @param number
     *            The lot number being bid for.
     * @param bidder
     *            The person bidding for the lot.
     * @param value
     *            The value of the bid.
     */
    public void bidFor(final int lotNumber,
        final Person bidder,
        final long value){
        final Lot selectedLot = getLot(lotNumber);
        if(selectedLot != null){
            final boolean successful =
                selectedLot.bidFor(new Bid(bidder, value));
            if(successful){
                System.out.println("The bid for lot number " + lotNumber
                    + " was successful.");
            } else{
                // Report which bid is higher.
                final Bid highestBid = selectedLot.getHighestBid();
                System.out.println("Lot number: " + lotNumber
                    + " already has a bid of: " + highestBid.getValue());
            }
        }
    }

}

3 个答案:

答案 0 :(得分:2)

Lot类是否有标记表明是否已购买?如果是那么

for(final Lot lot : lots){
   if (!lot.purchased) {
     System.out.println("not bought");
   }
}

BTW - 我注意到你在close方法中使用pre for-each样式迭代器。没有理由这样做,因为你也可以访问for-each中的各个Lot实例。

答案 1 :(得分:0)

我会将您希望Lot打印的信息添加到Lot.toString()我建议您的close()方法应该关闭()每个批次,并且该批次应该打印需要打印的任何内容。

答案 2 :(得分:0)

将属性添加到名为“wins”或类似名称的Person类型的Lot类中。

在bidFor方法中,在if(成功)块中,设置winner属性:

selectedLot.setWinner(bidder);

然后在遍历批次时,如果获胜者属性为空,请打印您尚未购买该批次的消息。

或者您可以使用:

if (lot.getHighestBid() == null)

取决于Lot类的实现方式,如果没有看到Lot类,很难知道。