java - 如何将一些值加载到对象数组的实例中?
问题描述
我正在做一些我在网上找到的练习,试图理解 OOP 等,我的问题如下,我有 2 个课程,主要是一个叫做 Book 的课程和一个叫做 Author 的课程。
作者拥有 3 个属性:字符串名称、字符串电子邮件和字符性别。Book posses 4: String bookname Author[] authors double price int qty
我的问题是,因为我没有也不明白 Author[] 应该是什么意思,是一个存储多个书籍作者的对象数组吗?如果是这样,我应该如何在主类上继续它,我应该创建对象 Author[] 的实例并使用 for 循环开始给他值吗?例如,该对象的值(姓名、电子邮件、性别)如何存储在 author1[] 中,我应该如何将值加载到该对象数组中?
试图自学java。
public class Book {
protected static final int QTY_DEF = 0;
private String name;
private Author[] authors;
private double price;
private int qty;
public Book(String name, Author[] authors, double price, int qty) {
this.name = name;
this.authors = authors;
this.price = price;
this.qty = qty;
}
}
public class Author {
private String name;
private String email;
private char gender;
public Author(String name, String email, char gender) {
this.name = name;
this.email = email;
this.gender = gender;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name;
String authorname;
String email;
int price;
int qty;
char gender;
Author[] author1 = new Author[3];
System.out.println("Author's name: ");
System.out.println("Author's email: ");
email = sc.nextLine();
System.out.println("Author's gender: ");
gender = sc.next().charAt(0);
解决方案
Author[] author1 = new Author[3];
意味着您正在创建一个最多容纳三个作者的数组。我们可以首先通过使用创建一些作者
Author billy = new Author("Billy","Billy@gmail.com",'M');
Author bob = new Author("Bob","Bob@gmail.com",'M');
Author shirly = new Author("Shirly","Shirly@gmail.com",'F');
然后我们可以通过这样做将它们放入数组中
author1[0] = billy;
author1[1] = bob;
author1[2] = shirly;
要获得某个作者,我们可以通过以下方式将其从数组中取出
author1[0]
这会给我们比利。但是,我们可能不会从对象中提取一些信息,例如姓名和电子邮件,因为这些字段目前是私有的。
将作者更改为
public class Author {
public String name;
public String email;
public char gender;
public Author(String name, String email, char gender) {
this.name = name;
this.email = email;
this.gender = gender;
}
}
通过此更改,您可以通过使用 author1 从 billy 那里获得一些信息
author1[0].name
这会给我们一个字符串,我们可以用它打印和做其他字符串的事情。
推荐阅读
- facebook - Facebook Pixel 问题,FB 支持人员表示未正确配置。Pixel Helper Extension 显示“Facebook 像素已激活 2 次”
- swiftui - 在navigationView中如何补充UIScrollView?
- python - QWebEngineView 并忽略证书错误
- python-3.x - 不知道在pyTelegramBotApi中判断如何处理键盘二
- javascript - 嗨,我该如何解决这个问题?
- c - 为什么将相同的地址发送到函数中?
- excel - 用于将数据拉入/重新计算工作簿然后每小时 PDF 的 Excel 的 VBA 代码最初运行良好最终开始 PDF 处理空白工作表
- python - 为所有子图设置 showgrid = False
- javascript - 在执行命令的行会中更改机器人昵称(Discord js)
- java - 我的 UML 图中是否需要另一个关联?