java - 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];
现在我收到错误不兼容的类型:作者无法转换为作者 []
解决方案
问题出在这里:
public Author[] getAuthors() {
for(int i = 0; i < authors.length; i++)
return Authors[i];
}
您声明要返回一个Author
但 return的数组Authors
,这是一个不同的类名。
我猜你的意思是写:
public Author[] getAuthors() {
return authors;
}
推荐阅读
- vue.js - 从 vue.js 中渲染列表中的数组访问数据
- c++ - 可变参数模板限定符
- java - 如何根据 href 链接动态更改 Thymeleaf 片段
- python - Jupyter Notebook 文件似乎保存为 html 而不是 .IPYNB
- python - 每次用户点击页面时 Django 中间件进行记录
- javascript - Sweet alert 2 的自定义样式
- opengl - 根据另一个纹理的亮度,从一个纹理到另一个纹理的平滑渐变过渡
- microsoft-graph-api - 异常 Azure AD B2C 使用 GraphServiceClient 设置自定义属性
- azure-data-factory - 我无法从 Azure 数据工厂中的 Impala 获取数据。通过查询超时异常复制活动
- powershell - 更新列表视图 SharePoint PowerShell