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