执行程序时,它在第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。
答案 0 :(得分:1)
您的next()
方法不应包含任何会返回无效值的情况,例如null
。如果没有下一个要返回的元素,则是hasNext()
方法的 job 返回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);
}
}
答案 1 :(得分:0)
还要检查module Services
module Trips
class TripPreviewResponseEntity < Grape::Entity
expose :id
expose :title
expose :duration
expose :total_price
expose :description
expose :details
expose :destinations do |trip, _options|
DestinationResponseEntity.represent(trip.destinations, trip_id: trip.id)
end
end
end
end
是否等于0:
nextCardSpade