gpt4 book ai didi

java - 为什么 getter 方法不返回任何对象的属性?

转载 作者:行者123 更新时间:2023-11-30 03:36:00 25 4
gpt4 key购买 nike

我的程序应该返回两个不同对象的不同属性。在我的主要方法中,我在创建新对象时将这些属性设置为参数。但是当我调用这些 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;
}

关于java - 为什么 getter 方法不返回任何对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27863715/

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