来自另一个 class 的带有字段的构造函数未定义?

Constructor with Field from another class is undefined?

新手 Java 教程指派我执行以下操作

  1. 在用户类中:
    1. 创建一个名为 readBook(Book book) 的方法
    2. readBook 应该打印,“<User> read <title>
  2. 在 BookRunner 中
    1. 为每本书创建一个作者。
    2. 另外,创建另一个用户并调用该用户的 readBook 方法,传入其中一本书

下面是我的代码:

public class Ex1_BookRunner {
    public static void main(String[] args) {
        Book firstBook = new Book("One Piece", "Oda-Sensei", 100, 123456);
        Book secondBook = new Book("Life of Megan Fox", "Micheal Bay", 200, 928765);
    }
}

public class User {
    public String name;
    public int age;
    public String location;
    public Book title;

    public String toString() {
        String description1 = "Name:" + name + " Age:"+ age + " Location:" + location; 
        return description1;
    }

    public void readBook(Book book) {
        System.out.println(name + " read " + title.title);
    }
}

public class Book {
    public String title;
    public User author;
    public int numPages;
    public int isbn;

    public Book(String title, User author, int numPages, int isbn) {
        this.title = title;
        this.author =  author;
        this.numPages = numPages;
        this.isbn = isbn;
    }

    public String toString() {
        String description = "Title:" + title + "Author"+ author.name + "Num. of pages" + numPages + "ISBN" + isbn; 
        return description;
    }   
}

我什至无法理解问题要我做什么。我有以下问题

  1. 问题让我用 readBook 方法打印 <User> read <title> 是什么意思?我设置 readBook 方法的方式是否正确解释了问题?

    方法中正确的代码应该是什么?

  2. 我在创建 author 时遇到问题,因为我收到错误 The constructor Book(String, String, int, int) is undefined 并且 Eclipse IDE 要我更改 [=17] 中的构造函数=] 从 (String, User, int, int)(String, String, int, int)。使用 User."Oda-Sensei"、"Oda-Sensei".name、"Oda-Sensei.User" 的实验都让我注意到我正在引入的变量 cannot be resolved.

从提问来看,好像作者就是用户。您在 main 方法中的构造函数调用正在传递字符串,因此您关于构造函数的错误。如果作者是用户,那么你应该改变你的电话:

public static void main(String[] args) {
    Book firstBook = new Book("One Piece", "Oda-Sensei", 100, 123456);
    Book secondBook = new Book("Life of Megan Fox", "Micheal Bay", 200, 928765);
}

public static void main(String[] args) {
    User odaSensei = new User();
    odaSensei.name = "Oda-Sensei";

    User michaelBay = new User();
    michaelBay.name = "Michael Bay";


    Book firstBook = new Book("One Piece", odaSensei, 100, 123456);
    Book secondBook = new Book("Life of Megan Fox", michaelBay, 200, 928765);
}

一定要设置authors的其他变量另一种方法是将authors的类型改为String,这样main方法不会有变化。

我还建议为用户添加一个构造函数,这样您就可以初始化新调用中的所有变量。

第二部分"Separately, create another user and call the readBook method on that user, passing in one of the created books"

告诉你创建一个全新的用户,例如鲍勃

User bobUser = new User();
bobUser.name="Bob"; 

然后让这位新用户阅读其中一本书:

bobUser.readBook(firstBook); 

目标是让阅读的书打印出来:

Bob read One Piece

为此,您需要更改 readBook 方法:

public void readBook(Book book) {
    System.out.println(name + " read " + title.title);
}

至:

public void readBook(Book book) {
    System.out.println(name + " read " + book.title);
}