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

标签 java arrays class methods constructor

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

我应该创建一个图书类来存储书名、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/

相关文章:

java - Java 中的 printf() 结构

javascript - 以Javascript形式Java创建字节数组

java - 对象可以有类中未定义的方法或变量吗?

java - 尝试将数字的数字放入数组中,但结果相反

c# - 有可能制作一个可以在多种语言中使用的库吗?

java - 在Java中其他 map 的基础上更新 map 中的值

c++ - 字符串运算符+(重载)char数组和string.in cpp中的不同行为

Python - 在字典中使用 numpy 数组作为键的替代方法

python - 如何从 tkinter 中的单选按钮获取值?

C++ - 在类中使用不是类对象属性的变量是不好的做法吗?