gpt4 book ai didi

java - 我如何从 toString 返回一个对象

转载 作者:行者123 更新时间:2023-12-02 04:46:03 25 4
gpt4 key购买 nike

我有一项作业,我需要在一个对话框中打印所有 5 本书的书名、isbn 编号和费用。我在 for 循环中很难做到这一点。当我尝试从 toString 获取书名时,我收到当前代码的错误,说不能从静态上下文引用非静态变量,但我认为这是因为我没有正确调用它。

public class Book
{
private String title;
private String author;
private String isbn;
private Double price;
private Publisher publisher;

public Book()
{
setTitle("");
setAuthor("");
setIsbn("");
setPrice(0.0);
setPublisher(new Publisher());
}

public Book(String t, String a, String i, double p, Publisher n)
{

setTitle(t);
setAuthor(a);
setIsbn(i);
setPrice(p);
setPublisher(n);
}

public void setTitle(String t)
{
title = t;
}

public String getTitle()
{
return title;
}

public void setAuthor(String a)
{
author = a;
}

public String getAuthor()
{
return author;
}

public void setIsbn(String i)
{
isbn = i;
}

public String getIsbn()
{
return isbn;
}

public void setPrice(double p)
{
price = p;
}

public double getPrice()
{
return price;
}

public void setPublisher(Publisher n)
{
publisher = n;
}

public Publisher getPublisher()
{
return publisher;
}

public double calculateTotal(int quantity)
{
return(price * quantity);
}

public String toString()
{
return( " Title " + title + " Author " + author + " Isbn " + isbn
+ " Price " + price + " Publisher " + publisher.toString());
}

}




import javax.swing. JOptionPane;

public class BookTest
{


public static void main(String args[])
{
double charge;


String dataArray[][] = {{"Abraham Lincoln Vampire Hunter","Grahame-Smith","978-0446563079","13.99", "Haper", "NY"},
{"Frankenstein","Shelley","978-0486282114","7.99","Pearson", "TX"},
{"Dracula","Stoker","978-0486411095","5.99","Double Day", "CA"},
{"Curse of the Wolfman"," Hageman","B00381AKHG","10.59","Harper", "NY"},
{"The Mummy","Rice","978-0345369949","7.99","Nelson", "GA"}};




Book bookArray[] = new Book[dataArray.length];

int quantityArray[] = {12, 3, 7, 23, 5};

for (int i = 0; i < dataArray.length; i++)
{
bookArray[i] = new Book(dataArray[i][0], dataArray[i][1], dataArray[i][2],
Double.parseDouble(dataArray[i][3]), new Publisher(dataArray[i][4], dataArray[i][5]));
}

String msg = " ";



for (int i = 0; i < bookArray.length; i++)
{

charge = bookArray[i].calculateTotal(quantityArray[i]);

msg += String.format("Title ", this.getTitle()); //stuff to print


}


JOptionPane.showMessageDialog(null, msg);

}




}

最佳答案

你想做的事:

for (int i = 0; i < bookArray.length; i++)
{

charge = bookArray[i].calculateTotal(quantityArray[i]);

msg += String.format("Title ", bookArray[i].getTitle());

}

您正在获取特定书籍的标题(由 bookArray[i] 引用)

关于java - 我如何从 toString 返回一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656864/

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