gpt4 book ai didi

java - 如何在主类中从另一个类的构造函数初始化数组字段?

转载 作者:行者123 更新时间:2023-11-30 07:51:32 24 4
gpt4 key购买 nike

很抱歉,如果这是一个愚蠢的问题,或者如果我没有正确地提出它,但我会尽力解释问题所在。

我应该创建一个图书类来存储书名、ISBN、价格和作者姓名。由于一本书可能有多个作者,我应该为此字段创建一个 Array 或 ArrayList。一切似乎都工作正常,但当我将数组字段初始化为字符串时,IDE 显示错误。我在这里错过了什么吗?有谁知道如何解决这个问题吗?

这是我的代码:

public class Books {
private String bookName;
private String ISBN;
private int price;
private String [] authorsList;

public Books (String bookName, String ISBN, int price, String[] authorsList){
this.bookName = bookName;
this.ISBN = ISBN;
this.price = price;
this.authorsList = authorsList;
}

public String toString(){
return "Book title: " + bookName +
"\nISBN: " + ISBN +
"\nPrice: " + price +
"\nAuthor: " + authorsList;
}

}

public static void main(String[] args) {          

Books book1 = new Books("Harry Potter","12345",10,"J. K. Rowling");

System.out.println(book1.toString());
}

}

最佳答案

如果你像这样编写System.out.println,你可以看到数组的内部

  System.out.println(book1.bookName + "\n" + book1.ISBN+"\n" + book1.price+"\n" +  Arrays.toString(authorsList));

你现在看不到它,因为它是一个数组,如果你这样写 System.out.println(book1.toString()); java 只显示它的位置。这就是为什么你看到像这样的 [Ljava.lang.String;@2a139a55

或者请将您的 toString 方法更改为现在显示的其实这样更好:

public String toString(){
return "Book title: " + bookName +
"\nISBN: " + ISBN +
"\nPrice: " + price +
"\nAuthor: " + Arrays.toString(authorsList);
}
public static void main(String[] args) {
Books book1 = new Books("Harry Potter","12345", 10, new String[]{"J. K. Rowling"});
System.out.println(book1.toString());
}

关于java - 如何在主类中从另一个类的构造函数初始化数组字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33287519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com