java - 从另一个类创建数组

标签 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. 

我不知道从这里该去哪里。

最佳答案

尝试这样的事情:

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() 来使第二种方法起作用,但是,您再次需要转换每个 w.nextToken() 返回到 WordCount 对象的字符串

关于java - 从另一个类创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16051106/

相关文章:

java - Easy-rules:使用构造函数在 POJO 中设置规则名称

java - 模拟 CloseableHttpClient 在测试时仍将连接传递到真实服务器

java - Tomcat在哪里调用Java?

java - 使用 Iterable 的类的多个迭代器

java - 从java执行终端命令

java - Jackson 映射到 Map 变量

java - 当值超过 150 时,int 值不相等?

java - Spring Bean 在应用程序重新启动后仍然存在吗?

java - 线程输出到 GUI 文本字段

java - 如何从 Java 枚举所有启用的 NIC 卡的 IP 地址?