Java 不兼容类型:无法将字符串转换为Word
我知道为什么会出现兼容性错误,但我想知道如何将字符串添加到程序中的类Java 不兼容类型:无法将字符串转换为Word,java,string,list,object,Java,String,List,Object,我知道为什么会出现兼容性错误,但我想知道如何将字符串添加到程序中的类类型的ArrayList中 在OO原则中,“WordContainer”是“Container”的一种类型,它包含“Words”,这是我在这里尝试实现的,但是如何向WordContainer添加一个字符串,该字符串包含一个Word类型的单词列表 public class Word { private String word; public String getWord() { return this.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() {
}
}
WordContainer类中的add方法需要一个单词作为参数,而不是字符串,因此您应该做的是 在Main.java中
container1.addWord(new Word(nextLine));
public Word(String word) {
this.word = word;
}
并在Word类中定义一个接受字符串的构造函数
在Word.java中
container1.addWord(new Word(nextLine));
public Word(String word) {
this.word = word;
}
WordContainer类中的add方法需要一个单词作为参数,而不是字符串,因此您应该做的是 在Main.java中
container1.addWord(new Word(nextLine));
public Word(String word) {
this.word = word;
}
并在Word类中定义一个接受字符串的构造函数
在Word.java中
container1.addWord(new Word(nextLine));
public Word(String word) {
this.word = word;
}
您的addWord()
方法需要一个Word
作为参数,但您在此行中向它传递了一个字符串
:
container1.addWord(nextLine);
这就是为什么会出现异常:不兼容的类型:字符串无法转换为Word
解决方案:
它需要:
container1.addWord(new Word(nextLine));
您需要使用字符串
参数实现构造函数
:
public Word(String word) {
this.word = word;
}
备选方案:
或者,您可以保留实际的主类代码,并实现一个方法,该方法可以访问字符串
,并将新的单词
对象添加到列表中:
public void addWord(String text) {
this.words.add(new Word(text));
}
您的addWord()
方法需要一个Word
作为参数,但您在此行中向它传递了一个字符串
:
container1.addWord(nextLine);
这就是为什么会出现异常:不兼容的类型:字符串无法转换为Word
解决方案:
它需要:
container1.addWord(new Word(nextLine));
您需要使用字符串
参数实现构造函数
:
public Word(String word) {
this.word = word;
}
备选方案:
或者,您可以保留实际的主类代码,并实现一个方法,该方法可以访问字符串
,并将新的单词
对象添加到列表中:
public void addWord(String text) {
this.words.add(new Word(text));
}
“我想知道如何将字符串添加到
类型的ArrayList中”——您不能。创建类型Word
列表的全部目的是避免出现Word
s以外的内容。您需要创建一个新的Word
对象。我是否需要在主类中与WordContainer对象一起创建Word对象?非常感谢。@azurefrog哦,对了,我该如何实现它作为解决方案?非常感谢!“我想知道如何将字符串添加到
类型的ArrayList中”——您不能。创建类型Word
列表的全部目的是避免出现Word
s以外的内容。您需要创建一个新的Word
对象。我是否需要在主类中与WordContainer对象一起创建Word对象?非常感谢。@azurefrog哦,对了,我该如何实现它作为解决方案?非常感谢!