如何调用返回单词数组的方法(给定输入序列)?

时间:2015-01-02 21:57:08

标签: java arrays eclipse string methods

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

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

}

现在我必须使用字符串 one two three four 作为参数调用方法 split 。如果我听起来天真,我道歉。我是编程新手。我一直在观看大量的教程,但是当我尝试调用该方法时,我的代码不断获得红色标记。

*代码的前14行(来自'公共类'到这里的代码')是提供给我的问题的一部分,所以他们不应该这样做。改变。如有必要,您可以更改其余代码。

编辑:

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

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

        object.split(s);

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

    }
}

基本上,我创建了另一个调用split方法的类。但是,我一直在拿红色标记。

3 个答案:

答案 0 :(得分:0)

在第一次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;

答案 1 :(得分:0)

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

首次浏览扫描程序t,了解作业给你的字符串数。

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

这意味着您至少还需要一步来填补它。现在你知道countWords,你给出的单词数量,你可以初始化你的数组。

String[] words = new String[countWords]

你有一个countWords数组 - 数字为空的String个对象。是时候填补它们了。

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

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

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

return words

最后一点:

请按照我在第一篇文章中的评论中的说法,阅读如何正确缩进。如果没有正确缩进,你真的无法编写/读取代码。

答案 2 :(得分:0)

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

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();

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

相关问题