【发布时间】:2017-11-17 19:18:35
【问题描述】:
我知道为什么会出现兼容性错误,但我想知道如何将字符串添加到
在 OO 原则中,“WordContainer”是“Container”的一种,它包含“Words”,这是我在这里尝试实现的,但是如何将字符串添加到具有Word 类型的单词列表?
public class Word {
private String word;
public String getWord() {
return this.word;
}
public void setWord(String word) {
this.word = word;
}
public Word() {
this.word = "";
}
}
容器类,其中包含 Word 类型的单词列表:
import java.util.*;
public class WordContainer {
private List < Word > words = new ArrayList < Word > ();
public List < Word > getWords() {
return this.words;
}
public void setWords(List < Word > words) {
this.words = words;
}
public void addWord(Word word) {
this.words.add(word);
}
public void display() {
words.forEach((word) - > {
System.out.println(word);
});
}
public WordContainer() {
}
}
主类:
public static void main(String[] args) {
Scanner naughty = new Scanner(System.in);
WordContainer container1 = new WordContainer();
while (true) {
String nextLine = naughty.nextLine();
if (nextLine.equals("")) {
container1.display();
System.exit(0);
}
container1.addWord(nextLine); // this bit doesn't work :(
}
}
【问题讨论】:
-
"我想知道如何将字符串添加到
<Word>类型的 ArrayList 中" -- 你不能。制作Word类型列表的全部意义在于将不是Words 的东西排除在外。 -
你需要创建一个新的
Word对象。 -
我需要在主类中创建一个单词对象和一个WordContainer对象吗?非常感谢。
-
@azurefrog 哦,对了,我怎样才能将它作为解决方案来实施?非常感谢!