我有这项作业,我想在一个对话框中全部打印出书名,isbn号和所有5本书的费用。我在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]引用)