从另一个类创建数组

时间:2013-04-17 03:45:03

标签: java

我有一个WordFreq类,它有一个processLines方法,可以从WordCount类创建一个数组。我有processLines方法的其他行访问WordCount没有问题。

我有:

public class WordCount{

    private String word;
    private int count;

    public WordCount(String w){
        word = w;
        count = 0;
    }

后面是类方法:

public class WordFreq extends Echo {

    String words, file;
    String[] wordArray;
    WordCount[] search;

WordFreq传递一个文本文件(在Echo中处理)和一串要搜索的单词。

public WordFreq(String f, String w){
    super(f);
    words = w;
}

public void processLine(String line){
    file = line;
    wordArray = file.split(" ");

    // here is where I have tried several methods to initialize the search
    // array with the words in the words variable, but I can't get the
    // compiler to accept any of them.

    search = words.split(" ");

    StringTokenizer w = new StringTokenizer(words);
    search = new WordCount[words.length()];

    for(int k =0; k < words.length(); k++){
        search[k] = w.nextToken();

我尝试了一些其他不起作用的事情。我尝试将search[k] =的权限转换为WordCount,但它不会超越编译器。我一直在变得不兼容。

Required: WordCount found: java.lang.String. 

我不知道从哪里开始。

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

String[] tokens = words.split(" ");
search = new WordCount[tokens.length];
for (int i = 0; i < tokens.length; ++i) {
    search[i] = new WordCount(tokens[i]);
}

第一次尝试的问题是words.split(" ")会产生String数组;你不能分配给WordCount数组变量。第二种方法的问题是words.length()words字符的数量,而不是令牌的数量。您可以使用w.countTokens()代替words.length()来使第二种方法有效,但是,您需要将String返回的每个w.nextToken()转换为{{1}对象。