[英]Why getter method doesn't return any object's attribute?
我的程序应为两个不同的对象返回不同的属性。 在我的主要方法中,我在创建新对象时将这些属性设置为参数。 但是,当我调用这些getter方法(我已经在一个单独的类中编写了该方法)时,可以根据需要发布该类),但它不会返回所有属性。 它仅打印出第一个属性(也设置为第一个参数),而不打印其他两个值。 我不知道我做错了什么。
我的代码:主类:
package main;
public class Main {
public static void main(String[] args) {
//creating object for book 1
Book book1 = new Book("The brief history of time", "111", new String[]{"S. hawking", "hawking's friends"});
//creating object for book 2
Book book2 = new Book("100 years of solitude", "222", new String[]{"G.marquez", "marquez's friend"});
System.out.println("All info for the first book: \n");
System.out.println("Name: " + book1.getName());
System.out.println("ISBN: " + book1.getIsbn());
System.out.println("Authors: " + book1.getAuthors());
System.out.println("\n\n");
System.out.println("All info for the second book: \n");
System.out.println("Name: " + book2.getName());
System.out.println("ISBN: " + book2.getIsbn());
System.out.println("Authors: " + book2.getAuthors());
}
}
书本类:
package main;
public class Book {
//variables
private String name;
private String isbn;
private String[] authors;
//constructors
public Book(String name, String isbn, String[] authors) {
this.name = name;
this.isbn = name;
this.authors = authors;
}
//setters
public void setName(String name) {
this.name = name;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public void setAuthors(String[] authors) {
this.authors = authors;
}
//getters
public String getName() {
return name;
}
public String getIsbn() {
return isbn;
}
public String[] getAuthors() {
return authors;
}
}
您需要迭代authors
数组才能在其中打印字符串。 像这样的东西:
System.out.println("All info for the first book: \n");
System.out.println("Name: " + book1.getName());
System.out.println("ISBN: " + book1.getIsbn());
for (String author : book1.getAuthors()) {
System.out.println("Author: " + author);
}
另外,您的Book
类构造函数中存在一个问题:
public Book(String name, String isbn, String[] authors) {
this.name = name;
this.isbn = name; // this.isbn is not name!
this.authors = authors;
}
一定是:
public Book(String name, String isbn, String[] authors) {
this.name = name;
this.isbn = isbn;
this.authors = authors;
}
当您要打印字符串数组时,可以使用this。
System.out.println(Arrays.toString(book1.getAuthors()));
Book构造函数存在问题:
public Book(String name, String isbn, String[] authors) { this.name = name; this.isbn = name; // you are setting isbn as name! this.authors = authors; }
我认为您需要定义getAuthors如何打印authors数组,例如打印Java数组的最简单方法是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.