我正在处理一个任务,我必须在文本中计算单词。我创建了一个包含Word
实例的ArrayList<Word>
。当我扫描文本时,如果它已经不在列表中,我只能向ArrayList添加一个单词。如果存在,我将用方法.increasNumber()
增加值。我该怎么做呢?如何在字符串中搜索对象的数组列表
public ArrayList<Word> list = new ArrayList<Word>();
public void readBook(String fileName) throws Exception {
String fileRead = fileName;
Scanner file = new Scanner(new File(fileRead));
while(file.hasNextLine()) {
addWord(file.nextLine());
}
}
private void addWord(String word) {
if (list.contains(word)) {
word.increasNumber);
} else {
list.add(new Word(word));
}
}
这里是我的Word
类:
public class Word {
String text;
int count = 0;
public Word(String text) {
this.text = text;
}
public String toString() {
return text;
}
public int getNumber() {
return count;
}
public void increasNumber() {
count++;
}
}
你的'list'中充满了'Word'对象,你正在检查'list'是否包含'String'对象。 – gonzo
我们可以看到你的'Word'类吗? – gonzo