首页 > 解决方案 > Java中类内数组的getter错误

问题描述

我在类中的构造函数需要使用一组 Authors 而不是单个 Author 对象。

我已经为其他所有内容编写了代码,但 Array 似乎表现不佳。我只包含了与数组相关的代码。

class myClass {
   ...   
   private Author[] authors;
   ...

   public Book(String name, Author[] authors, double price, int qtyInStock) {
        this.name = name;
        this.authors = authors;
        this.price = price;
        this.qtyInStock = qtyInStock;
    }
    public Book(String name, Author[] authors, double price) {
        this.name = name;
        this.authors= authors;
        this.price = price;

   ...

   public void setAuthors(Author[] authors) {
      this.authors = authors;
   }
   public Author[] getAuthors() {
      for(int i = 0; i < authors.length; i++)
      return authors[i];
   }

   ...

   public void printAuthors() {
        for (Author a : getAuthors())
           System.out.println(a);
    }
    public String toString() {
        if(lenAuthor == 1)
            return String.format(name + " by 1 author");
        else
            return String.format(name + " by " + lenAuthor + "author");
    }
   ...

我得到的错误是它找不到作者符号。我将如何修复我的代码以便 getAuthors 编译?

更新:我将返回更改为

return authors[i];

现在我收到错误不兼容的类型:作者无法转换为作者 []

标签: javaarraysclass

解决方案


问题出在这里:

public Author[] getAuthors() {
  for(int i = 0; i < authors.length; i++)
  return Authors[i];
}

您声明要返回一个Author但 return的数组Authors,这是一个不同的类名。

我猜你的意思是写:

public Author[] getAuthors() {
  return authors;
}

推荐阅读