编辑检查ArrayList是否包含String。如果没有,添加字符串
许多用户都评论说类的话是没用的,这可能是在这种情况下正确的。我添加它的原因是因为我稍后在程序中需要它。
该程序有3个类 - WordList,Word和测试类。我试图让'readBook'方法读取文件,并将每个单词发送到方法'addWord'。方法addWord将检查ArrayList allWords是否包含该单词。如果没有,addWord会将该单词添加到数组中,并将其发送到Word类。当我运行程序时,没有任何反应。我试图打印出allWords.size(),它返回0
类单词一览:
public class WordList {
String nextWord;
ArrayList<String> allWords = new ArrayList<String>();
public void readBook (String filename) throws Exception{
File file = new File(filename); //File has one word on each line.
Scanner innFile = new Scanner(file);
for (int i = 0; i<file.length(); i++){
if(innFile.hasNextLine()){
nextWord = innFile.nextLine();
addWord(nextWord);
}
}
}
private void addWord(String word){
for (String check : allWords){
if (!check.equalsIgnoreCase(word)){
allWords.add(word);
new Word(word);
}
else if(check.equalsIgnoreCase(word)){
System.out.println("The word allready exsist.");
}
else{
System.out.println("Something went wrong.");
}
}
}
类词语:
public class Word {
String word;
ArrayList<String> allWords = new ArrayList<String>();
Word(String text){
word = text;
allWords.add(word);
System.out.print(allWords);
}
测试类:
public class TestClass {
public static void main (String[] args) throws Exception{
WordList list = new WordList();
list.readBook("path.../scarlet.text");
WordList newList = new WordList();
System.out.println(newList.numberOfWords());//A method printing out allWords.size()
}
}
您可能不想一般使用'ArrayList'类或任何'List' - 这是一个可以通过'Set'轻松解决的经典问题。特别是,您可以使用'HashSet'或'LinkedHashSet'实现。 – Clashsoft
另外,为什么每个单词都包含一个“wordList”呢?这似乎没有多大意义。 – Clashsoft
如果你不想'allWords'包含重复项,声明它为'Set'(或'TreeSet ',如果你想要按字母顺序排列的话)。 –