【问题标题】:Returns the nth short word in an array in Java返回 Java 数组中的第 n 个短字
【发布时间】: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] 并且一切正常运行。感谢您的时间/帮助!

标签: java arrays methods


【解决方案1】:

我看到的几个问题 -

  1. 如果条件不满足,则不会返回空字符串。

  2. 你正在返回nthShortWord[i],这将导致语法错误,因为nthShortWord是一个整数,你不能为它们下标,你应该返回words[i]

代码-

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 words[i];
    }
    return "";
}

【讨论】:

  • 谢谢!改回words[i]解决了问题,问题运行不正常!
  • 抱歉,程序现在*运行正常!
  • 我做到了!我只是在等待时间限制结束。再次感谢您的帮助!
【解决方案2】:

您的方法应该在所有可能的执行路径中返回一个字符串值,从而导致错误。你可以这样做:

public String nthShortWord(String[] words, int n)
{
int nthShortWord = 0;
String shortWord="notFound";
for (int i = 0; i < words.length; i++)
{
   if (words[i].length()<=3) nthShortWord++;
   if (nthShortWord==n) {
     shortWord =nthShortWord[i];
     break;
   }
} 
return shortWord;
}

还要注意break 语句,因为您需要在找到第一个短词时退出循环。

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2011-08-03
    • 1970-01-01
    • 2014-08-13
    • 2014-10-31
    • 2015-03-29
    • 1970-01-01
    • 2020-04-24
    • 2018-12-12
    相关资源
    最近更新 更多