【问题标题】:Incompatible types: String cannot be converted to Word不兼容的类型:字符串无法转换为 Word
【发布时间】:2017-11-17 19:18:35
【问题描述】:

我知道为什么会出现兼容性错误,但我想知道如何将字符串添加到 类型的 ArrayList,它是程序中的一个类。

在 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 :(
  }


}

【问题讨论】:

  • "我想知道如何将字符串添加到 &lt;Word&gt; 类型的 ArrayList 中" -- 你不能。制作Word 类型列表的全部意义在于将不是Words 的东西排除在外。
  • 你需要创建一个新的Word对象。
  • 我需要在主类中创建一个单词对象和一个WordContainer对象吗?非常感谢。
  • @azurefrog 哦,对了,我怎样才能将它作为解决方案来实施?非常感谢!

标签: java string list object


【解决方案1】:

WordContainer 类中的 add 方法需要一个 Word 作为参数而不是字符串,所以你应该做的是

在 Main.java 中

  container1.addWord(new Word(nextLine)); 

并在您的 Word 类中定义一个接受字符串的构造函数

在 Word.java 中

public Word(String word) {
    this.word = word;
}

【讨论】:

    【解决方案2】:

    您的 addWord() 方法需要 Word 作为参数,但您在此行中将 String 传递给它:

    container1.addWord(nextLine);
    

    这就是你得到异常的原因:Incompatible types: String cannot be converted to Word

    解决方案:

    必须是:

    container1.addWord(new Word(nextLine));
    

    您需要使用String 参数实现constructor

    public Word(String word) {
        this.word = word;
    }
    

    替代方案:

    或者您可以保留您的实际主类代码并实现一个接受String 的方法并将一个新的Wordobject 添加到您的列表中:

    public void addWord(String text) {
        this.words.add(new Word(text));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多