0

配列リストが空の場合、このコードはエラーを返します。エラーを回避し、空の場合は null を返すためにコードを追加する必要があります。ありがとう

public Comment findMostHelpfulComment()
{
    Iterator<Comment> it = comments.iterator();
    Comment best = it.next();
    while(it.hasNext()) 
    {
        Comment current = it.next();
        if(current.getVoteCount() > best.getVoteCount()) {
            best = current;
        }
    }

return best;
}
4

2 に答える 2

3
public Comment findMostHelpfulComment()
{
    if (comments.isEmpty()) {
        return null;
    }

    // rest of method
}

nullまたは、ループを少し作り直せば、最高のコメントから始めることができます。

public Comment findMostHelpfulComment()
{
    Comment best = null;

    for (Comment current: comments) {
        if (best == null || current.getVoteCount() > best.getVoteCount()) {
            best = current;
        }
    }

    return best;
}
于 2013-02-26T23:14:24.947 に答える
0
public Comment findMostHelpfulComment()
{
    Iterator<Comment> it = comments.iterator();
    Comment best = new Comment();
    best.setVoteCount(0);
    while(it.hasNext()) 
    {
        Comment current = it.next();
        if(current.getVoteCount() > best.getVoteCount()) {
            best = current;
        }
    }
    return best;
}

これを試して。空の配列でも問題はありませんが、;に設定されたダミーCommentを返します。voteCount0

于 2013-02-26T23:17:43.993 に答える