2013-02-26 3 views
0

Этот код вернет ошибку, если список массивов пуст. Мне нужен код для добавления, чтобы избежать ошибки и возвращать значение null, если оно пустое. БлагодаряНужно добавить код, чтобы вернуть пустой массив как 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; 
} 
+0

Добро пожаловать в SO! К сожалению, это не тот тип вопросов, который мы ожидаем от SO. Прочитайте [ask], чтобы узнать, как мы ожидаем ответа. –

ответ

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; 
} 
+0

Омг ... Клянусь, я попробовал это. Спасибо, сейчас работает. Боже, я чувствую себя глупым. –

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 с voteCount, установленный в 0;

Смежные вопросы