【问题标题】:How do I call a method that returns an array of words (given an input sequence)?如何调用返回单词数组的方法(给定输入序列)?
【发布时间】:2015-01-02 21:57:07
【问题描述】:

我被要求创建一个方法,在该方法中我输入一个字符串序列并创建一个数组来存储字符串的单词。到目前为止,这就是我所拥有的:

public class Tester{
    public static String[] split(String s) {
        // determine the number of words
        java.util.Scanner t = new java.util.Scanner(s);
        int countWords = 0;
        String w;
        while (t.hasNext()) {
            w = t.next();
            countWords++;
        }
    // create appropriate array and store the string’s words in it
        // code here
        String[] words = new String[4]; // Since you are using an array you have to declare
        // a fixed length.
        // To avoid this, you can use an ArrayList 
        // (dynamic array) instead.
        while (t.hasNext()) {
            w = t.next();
            words[countWords] = w;
            countWords++;
        }
        return words;
    }

}

现在我必须以字符串一二三四作为参数调用方法split。如果我听起来很天真,我很抱歉。我是编程新手。我一直在观看大量关于此的教程,但是当我尝试调用该方法时,我的代码不断出现红色标记。

*代码的前 14 行(从“public class”到“code here”)是给我的问题的一部分,因此不应更改它们。如有必要,您可以更改其余代码。

编辑:

如何创建一个调用 split 方法的 main 方法?这是我尝试过的:

class Demo
{
    public static void main(String[]args)
    {
        Tester object = new Tester();

        object.split(s);

        System.out.println(words[i]);

    }
}

基本上,我创建了另一个调用 split 方法的类。但是,我不断收到红色标记。

【问题讨论】:

标签: java arrays eclipse string methods


【解决方案1】:

在第一个while (t.hasNext ()) 循环之后,您的t 扫描器已经耗尽。

你需要重新创建它,让它从头开始:

String[] words = new String[countWords];  // the size is countWords
t = new java.util.Scanner (s);            // recreate the scanner
int index = 0;
while (t.hasNext()) {
    words[index++] = t.next();
}
return words;

【讨论】:

    【解决方案2】:

    在 cmets 中有一个注释。由于您使用的是字符串数组String[] words,因此您需要确定地知道数组的长度,以便正确初始化、填充并使用它。

    您在扫描器中的第一次循环,t,会了解您的作业给了您多少字符串。

    int countWords = 0;
    while (t.hasNext()) {
        w = t.next();
        countWords++;
    } 
    

    这意味着您至少需要多走一步才能将其填满。既然你知道了countWords,给你的字数,你就可以初始化你的数组了。

    String[] words = new String[countWords]

    您有一个 countWords-in-number 空 String 对象数组。是时候把它们填满了。

    我们现在将进行第二个循环,并填充我们的 words 字符串数组

    int i = 0;
    while (t.hasNext()) {
        words[i] = t.next();
        i++;
    }
    

    就是这样。现在将其返回给调用者。

    return words

    最后一点:

    请阅读如何正确缩进,正如我在对您的第一篇文章的评论中所说的那样。如果缩进不正确,您真的无法编写/读取代码。

    【讨论】:

      【解决方案3】:

      首先,您根本不需要计算字数。相反,这可以简单地完成为

      ArrayList<String> wordsList = new ArrayList<String>(); This list will contain all your words
      t = new java.util.Scanner (s);// scanner
      while (t.hasNext()) {
          wordsList.add(t.next());
      }
      return wordsList.toArray();
      

      使用它的好处是您不需要为数组或列表初始化任何大小。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-14
        • 2020-08-25
        • 2015-11-24
        • 1970-01-01
        • 2013-12-15
        • 1970-01-01
        相关资源
        最近更新 更多