【问题标题】:Printing an array statement打印数组语句
【发布时间】:2014-04-20 23:38:41
【问题描述】:

当我尝试在单独的课程中打印 myWords 时,我得到一个空白语句。我很确定代码是正确的,但我无法让它打印出我想要的单词。请帮忙!

public String[] multiLetter (int n, char included)
//public String[] multiLetter(int n, char included)
//returns an array of words with at least m occurrences
//of the letter included

{   
    for (int i = 0 ; i < words.size() ; i++)    
    {
        int repeatCounter = 0;
        for (int j = 0 ; j < words.get(i).length(); j ++)
        {   
            if (included == words.get(i).charAt(j))
            {
                repeatCounter ++;
            }
        }//closes inner for loop 

        if (repeatCounter >= n)
        {
            myWords.add(words.get(i));
        }
    }

    String [] array = new String [myWords.size()];
    return myWords.toArray(array);              
}   

【问题讨论】:

  • 你永远不会打印任何东西。
  • 您遗漏了足够多的相关信息,我们无法为您提供帮助。
  • 我们需要查看您尝试打印数组的类
  • myWords 是如何定义的?您可以在方法的第一行添加以下代码:List&lt;String&gt; myWords = new ArrayList&lt;String&gt;();。当 myWords 是局部变量时就足够了。

标签: java arrays words


【解决方案1】:

首先:使用您编码的方式,您必须接收一个字符串列表作为参数。 第二:您必须创建 myWords 变量。 我认为你的代码应该没问题:

public String[] multiLetter (int n, char included, List<String> words)
//public String[] multiLetter(int n, char included)
//returns an array of words with at least m occurrences
//of the letter included
{   
    List<String> myWords = new ArrayList<String>();
    for (int i = 0 ; i < words.size() ; i++)    
    {
        int repeatCounter = 0;
        for (int j = 0 ; j < words.get(i).length(); j ++)
        {   
            if (included == words.get(i).charAt(j))
            {
                repeatCounter++;
            }
        }//closes inner for loop 

        if (repeatCounter >= n)
        {
            myWords.add(words.get(i));
        }
    }
    return (String[])myWords.toArray();             
}  

【讨论】: