我知道为什么会出现兼容性错误,但我想知道如何将String添加到类型为<的ArrayList中。 Word>这是该计划中的一个类。
在OO原则中," WordContainer"是一种"容器",它包含" Words",这是我试图在这里实现的,但是如何将String添加到WordContainer中一个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 :(
}
}
答案 0 :(得分:0)
从WordContainer类添加的方法是期望Word作为参数而不是String,所以你应该做的是
Main.java中的
with (lookupAll(".chart-legend").first()) {
getChildList()?.clear()
vbox {
label("Line 1")
label("Line 2")
label("Line 3")
}
}
在Word类中定义一个接受String
的构造函数在Word.java中
container1.addWord(new Word(nextLine));
答案 1 :(得分:0)
您的addWord()
方法需要Word
作为参数,但您在此行中传递了String
:
container1.addWord(nextLine);
这就是你得到例外的原因:Incompatible types: String cannot be converted to Word
<强>解决方案:强>
需要:
container1.addWord(new Word(nextLine));
您需要使用constructor
参数实现String
:
public Word(String word) {
this.word = word;
}
<强>替代:强>
或者您可以保留实际的主类代码并实现一个方法来访问String
并在列表中添加新的Word
对象:
public void addWord(String text) {
this.words.add(new Word(text));
}