我正在做一些我在网上找到的练习,试图理解OOP等,我的问题如下,我有2个类,主要是一个名为“Book”的类和一个名为“Author”的类。
作者拥有 3 个属性: 字符串名称、字符串电子邮件和字符性别。 本书拥有4个: 字符串书名 作者[] 作者 双倍价格 整数数量
我的问题是,因为我不明白也不明白 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]
这会给我们比利。但是,我们可能不会从对象中获取某些信息,例如姓名和电子邮件,因为这些字段目前是私有(private)的。
将作者更改为
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
这将为我们提供一个字符串,我们可以用它打印并执行其他字符串操作。
关于java - 如何将一些值加载到对象数组的实例中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57438412/