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);
}
}
所以我运行此代码并收到以下错误:
运行:
线程中的异常&#34; main&#34; java.lang.RuntimeException:无法编译的源代码
- 非静态方法getPrice(java.lang.String)无法从BookStore.main中的静态上下文引用(BookStore.java:26)
Java结果:1
建立成功(总时间:2秒)
这让我感到困惑,因为我试图仅仅强调静态&#39; getPrice()前面的修饰符,但会产生一大堆其他错误。也许你们其中一个人可以帮助我..?任何帮助表示赞赏。
答案 0 :(得分:0)
像这样:
public static void main(String[] args) {
BookStore bs = new BookStore();
String name = "";
do {
name = bs.input("Type the name of an item");
float price;
price = bs.getPrice(name);
if (price > 0) {
output(name + " = " + price);
} else {
output(name + " was not found");
}
} while (name.length() > 0); // type nothing to quit
}