Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从另一个类创建数组_Java - Fatal编程技术网

Java 从另一个类创建数组

Java 从另一个类创建数组,java,Java,我有一个WordFreq类,它有一个processLines方法,该方法从WordCount类创建一个数组。我有processLines方法访问WordCount的其他行,没有问题 我有: public class WordCount{ private String word; private int count; public WordCount(String w){ word = w; count = 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();

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

试试这样的方法:

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

第一次尝试的问题是
words.split(“”)会导致
字符串
数组;不能将
字数
数组变量赋值。第二种方法的问题是
words.length()
words
中的字符数,而不是令牌数。通过使用
w.countTokens()
代替
words.length()
,您可能可以使第二种方法起作用,但是,同样,您需要将
w.nextToken()
返回的每个
字符串
转换为
WordCount
对象。

要更快地获得更好的帮助,请发布一个。这就成功了!我在其他一些方法中使用.length()时出现了一些运行时错误。如果你没有指出这一点,我可能会被困在那里一段时间。我已经让程序正常运行了。非常感谢。
String[] tokens = words.split(" ");
search = new WordCount[tokens.length];
for (int i = 0; i < tokens.length; ++i) {
    search[i] = new WordCount(tokens[i]);
}