0

我有一个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. 

我不知道从这里去哪里。

4

1 回答 1

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()WordCount对象。

于 2013-04-17T03:47:30.007 回答