【发布时间】:2016-03-02 07:54:27
【问题描述】:
public class BookStore {
/**************************************************
Kim works in the school bookstore, selling pens, notebooks, etc.
They have prices written in a notebook. When prices change
they must cross out old prices - that's messy. They want
a computer program that stores and displays prices.
Item names and prices are stored in PARALLEL ARRAYS.
***************************************************/
String[] items = {
"pencil", "pen", "sharpie", "notebook A", "notebook B",
"eraser", "tippex", "usb stick", "glue", "tape"
};
float[] prices = {
0.75f, 1.50f, 1.20f, 1.90f, 2.50f,
0.50f, 1.75f, 5.00f, 1.25f, 2.00f
};
public static void main(String[] args) {
String name = "";
do {
name = input("Type the name of an item");
float price;
price = getPrice(name);
if (price > 0) {
output(name + " = " + price);
} else {
output(name + " was not found");
}
} while (name.length() > 0); // type nothing to quit
}
float getPrice(String name) // search for name, return price
{ // the price is not case-sensitive
for (int x = 0; x < prices.length; x = x + 1) {
if (items[x].equalsIgnoreCase(name)) // not cases-sensitive
{
return prices[x];
}
}
return 0.00f;
}
static public String input(String prompt) {
return javax.swing.JOptionPane.showInputDialog(null, prompt);
}
static public void output(String message) {
javax.swing.JOptionPane.showMessageDialog(null, message);
}
}
所以我运行这段代码,我得到以下错误:
运行:
线程“main”java.lang.RuntimeException 中的异常:无法编译的源代码
- 无法从 BookStore.main(BookStore.java:26) 的静态上下文中引用非静态方法 getPrice(java.lang.String)
Java 结果:1
构建成功(总时间:2 秒)
这令人困惑,因为我试图在 getPrice() 前面添加“静态”修饰符,但这会产生大量其他错误。也许你们中的一个可以帮助我..?任何帮助表示赞赏。
【问题讨论】:
-
getPrices () 是一个实例方法,并且应该是,因为在其中访问的价格和项目是实例属性,是一个特定 BookStore 实例的属性,而不是整个 BookStore 类的属性。在你的 main 中实例化一个 BookStore 实例:
BookStore b = new BookStore ()你可以调用b.getPrices () -
还有this
标签: java arrays methods static-methods