从阵列打印

时间:2017-07-28 03:00:49

标签: java arrays

我在使用字符串方法打印我的引用时遇到问题。我用一个数组来讲述其中一个构造函数'参数。为了让我使用toString,我必须包括所有变量,包括参考,其中包括来自另一个构造函数的参数。

Author au10 = new Author("Dan Gheesling", 29);
        MyDate my10 = new MyDate(2011);
        books[9] = new Book(au10, "Big Brother - The Survival Guide", my10, 32.99);


       for (Book book : books) {


           System.out.println(book);
           System.out.println();
       }

public Book(Author author, String title, MyDate publishing, double price)   {

        this.author = author;
        this.title = title;
        this.publishing = publishing;
        }

@Override
public String toString()    {


    return  Author.class.toGenericString() + "\n" +
            "Title: " + this.title + "\n" + 
            "Publication Date: " + this.publishing + "\n" +
            "Price: " + this.price;




}

2 个答案:

答案 0 :(得分:1)

您可以直接在增强型for循环中打印结果,而不是覆盖toString()方法,如下所示:

for(Book book:books){

       System.out.println("Title: " + book.title + "\n" + 
        "Publication Date: " + book.publishing + "\n" +
        "Price: " + book.price;);
       System.out.println();
   }

您可以尝试在yout toString方法中使用以下代码

public String toString(){

//whatever is the name of variable in author class
return  this.author.name + "\n" + 
         this.author.value + "\n" + 
        "Title: " + this.title + "\n" + 
        "Publication Date: " + this.publishing + "\n" +
        "Price: " + this.price;

}

答案 1 :(得分:0)

给定的代码不完整。像Author类一样缺少一些细节。 您的代码应如下所示:

class Author {
String str;
int i;
    Author(String s, int a)
    {
       s =str;
        a=i;
    }
}

与作者相同,您将创建 MyDate 预订类。

我在您的代码中完成了一些修改。

 public Main(Author author, String title, MyDate publishing, double price)   {
        this.author = author;
        this.title = title;
        this.publishing = publishing;
        }
@Override
public String toString()    {
    return  author + "\n" +
            "Title: " + this.title + "\n" +
            "Publication Date: " + this.publishing + "\n" +
            "Price: " + this.price;
}

 public static void Main(String[] args) {
     Author au10 = new Author("Dan Gheesling", 29);
        MyDate my10 = new MyDate(2011);
       Book b = new =Book("au10", "Big Brother - The Survival Guide", "my10", 32.99);
           System.out.println(b);
    }