检查 ArrayList 是否包含字符串.如果没有,请添加该字符串 [英] Check through an ArrayList if it contains a String. If it doesn't, add that String
问题描述
编辑
许多用户评论说 Class Word 没有用,这在这种情况下可能是正确的.我添加它的原因是因为我稍后在程序中需要它.
这个程序有 3 个类 - WordList、Word 和一个测试类.我试图让方法readBook"读取文件,并将每个单词发送到方法addWord".方法 addWord 将检查 ArrayList allWords 是否包含该词.如果没有,addWord 会将单词添加到数组中,并将其发送到 Word 类.当我运行程序时,没有任何反应.我试图打印出返回 0 的 allWords.size().
This program has 3 classes - WordList, Word and a test class. I'm trying to get the method 'readBook' to read through a file, and send every word over to the method 'addWord'. Method addWord will check if the ArrayList allWords contains that word. If it doesn't, addWord will then add the word to an array, aswell as to send it over to class Word. When I run the program, nothing happens. I tried to print out allWords.size(), which returned 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()
}
}
推荐答案
您正在 for (String check : allWords) 内填充
WordList
类的 allWords
列表代码>.最初它是空的,因此它永远不会进入 for 循环,并且 allWords
永远不会被填充.反过来new Word(word)
不会被调用,词类的allWords
为空.
You are populating allWords
list of WordList
class inside for (String check : allWords)
. Initially it would be empty hence it will never enter the for loop and allWords
will never get populated. In turn new Word(word)
will not be called and allWords
of word class will be empty.
这篇关于检查 ArrayList 是否包含字符串.如果没有,请添加该字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!