0

执行我的程序时,它在第 13 行一直显示“null”我想知道我的算法出了什么问题,因为它一直打印 null。

private class SpadeIterator implements Iterator<Card>{
    private int nextCardSpade;
    private List<Card> cards;
    private int count=0;
    private SpadeIterator(List cards) {
        this.cards=cards;
        this.nextCardSpade = cards.size()-1;
    }

    @Override
    public boolean hasNext() {
        count++;
        if(nextCardSpade<0)
            return false;
        //nextCardSpade--;
        return true;
    }

   @Override
    public Card next() {

        int i=0;
        this.count=i;
        Card temp = cards.get(nextCardSpade);

        while(hasNext()){    //find SPADES
            temp=cards.get(nextCardSpade--);
            i++;

            if(temp.suit.value == Suit.SPADES.value)
                return temp;
        }
        //DONT MOVE
        return null;
        //nextCardSpade--;      //DONT DELETE

    }
}

当前结果

结果旨在显示 13 个黑桃,最后不返回 null。

4

2 回答 2

0

您的next()方法不应包含任何会返回无效值的情况,例如null. 如果没有要返回的下一个元素,则hasNext()方法的工作是返回false以防止您调用next().

所以你的代码应该看起来更像

class SpadeIterator implements Iterator<Card>{
    private int spadesCounter = 0;
    private Iterator<Card> cardsIt;

    private SpadeIterator(List<Card> cards) {
        cardsIt = cards.iterator();
    }

    @Override
    public boolean hasNext() {
        return spadesCounter<13; // we can't put spacesCounter++ here because 
                                 // we should be able to call `hasNext()` many times
                                 // and still get same answer,
                                 // so `hasNext()` shouldn't change any state 
                                 // (at least one which could cause changing its result)
    }

    @Override
    public Card next() {
        Card temp = cardsIt.next(); //if our `hasNext()` returned `false` but we 
                                    //didn't check or ignored it, this will CORRECTLY 
                                    //throw NoSuchElementException 
        while(temp.suit.value != Suit.SPADES.value){
            temp = cardsIt.next();
        }
        spadesCounter++;
        return temp;
    }
}

或者,如果您只是想遍历列表并仅打印选定的元素,则可以使用带有过滤功能的流,例如

List<Card> cards = ...//not really important how get it
cards.stream()
     .filter(card -> card.suit.value == Suit.SPADES.value)
     .forEach(card -> System.out.println(card));

甚至更简单

for (Card card : cards){
    if(card.suit.value == Suit.SPADES.value){
        System.out.println(card);
    }
}
于 2019-01-20T15:15:13.583 回答
0

检查是否也nextCardSpade等于 0:

if (nextCardSpade <= 0)
于 2019-01-20T14:55:59.277 回答