【发布时间】:2015-06-30 04:29:38
【问题描述】:
我需要编写一个程序来返回数组中的第 n 个短字。这是我目前所拥有的:
public class Words
{
/**
Returns the nth short word (length <= 3) in an array.
@param words an array of strings
@param n an integer > 0
@return the nth short word in words, or the empty string if there is
no such word
*/
public String nthShortWord(String[] words, int n)
{
int nthShortWord = 0;
for (int i = 0; i < words.length; i++)
{
if (words[i].length()<=3) nthShortWord++;
if (nthShortWord==n) return nthShortWord[i];
}
}
}
它没有正确运行并说我需要返回一个值,但我已经是了。
任何/所有帮助将不胜感激!
【问题讨论】:
-
如果你的数组不包含 n 个短单词会怎样?您仍然应该返回正确的东西???所以在循环之后返回一个
null或其他东西。 -
有道理!我在循环之后添加了 return null 但它仍然没有正确运行。
-
什么错误???另请查看 Anand 的答案。您应该返回
words[i]而不是nthShortWord[i]。 -
我将返回更改为 words[i] 并且一切正常运行。感谢您的时间/帮助!