import java.util.*;
public class ComicBooks {
public ComicBooks(){
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
HashMap quality = new HashMap();
float price1 = 3.00F;
quality.put("mint",price1);
float price2 = 2.00F;
quality.put("near mint",price2);
float price3 = 1.50F;
quality.put("very fine",price3);
float price4 = 1.00F;
quality.put("fine",price4);
float price5 = 0.50F;
quality.put("good",price5);
float price6 = 0.25F;
quality.put("poor",price6);
Comic[] comix = new Comic[3];
comix[0] = new Comic("AMAZING sPIDER-MAN","1a","very fine",5_000.00F);
comix[0].setPrice((Float)quality.get(comix[0].condition));
comix[1] = new Comic("Incredible Hulk","181","near mint",240.00F);
comix[1].setPrice((Float)quality.get(comix[1].condition));
comix[2] = new Comic("Cerebus","1A","good ",144.00F);
comix[2].setPrice((Float)quality.get(comix[0].condition));
for (Comic comix1 : comix) {
System.out.println("Title:" + comix1.title);
System.out.println("Issue:" + comix1.issueNumber);
System.out.println("Condition" + comix1.condition);
System.out.println("Price: $ " + comix1.price + "\n");
}
}
class Comic{
String title;
String issueNumber;
String condition;
float basePrice;
float price;
Comic(String inTitle,String inIssueNumber,String inCondition,
float inBasePrice){
title = inTitle;
issueNumber = inIssueNumber;
condition = inCondition;
basePrice = inBasePrice;
}
void setPrice(float factor){
price = basePrice*factor;
}
}
}
在41行遇到无法从静态上下文中引用非静态 变量 this
this变量是当前对象指针,只能在非静态方法中访问,非静态方法又叫实例对象方法,必须通过对象访问的方法,这是Java语法规定的。静态方法又叫类方法,不需要实例化而是通过类名称调用的方法,与实例无关,当然没有必要也不能访问this对象了啊。
Comic类里面需要使用的字段、函数都要加上public
我知道了,我吧Comic类放到了Comicbooks类中间,结果就无法访问。
问题在于你把 class Clerk 放到了 public class fengzhuang 内部
Clerk 成了fengzhuang 的非静态内部类,属于fengzhuang 的一个成员
在静态方法main中不能访问非静态的成员,也就不能直接new Clerk()
只能通过外部类的对象访问。
把Clerk clerk1=new Clerk("职员一",25,2012.12f);改成:
Test.Clerk clerk1=new Test().new Clerk("职员一",25,2012.12f);
或者把class Clerk放到fengzhuang 类外面就好了。
提问者评价
非常感谢,说得很透。
我知道了,我吧Comic类放到了Comicbooks类中间,结果就无法访问。
问题在于你把 class Clerk 放到了 public class fengzhuang 内部
Clerk 成了fengzhuang 的非静态内部类,属于fengzhuang 的一个成员
在静态方法main中不能访问非静态的成员,也就不能直接new Clerk()
只能通过外部类的对象访问。
把Clerk clerk1=new Clerk("职员一",25,2012.12f);改成:
Test.Clerk clerk1=new Test().new Clerk("职员一",25,2012.12f);
或者把class Clerk放到fengzhuang 类外面就好了。
提问者评价
非常感谢,说得很透。
静态方法不可以直接调用静态的方法,如果想调用的话,new这个非静态方法的实例,然后用实例去调方法。
静态方法不可以直接调用非静态的方法。如果想调用的话,new这个非静态方法的实例,然后用实例去调方法。
this 是不能在静态方法中使用的
必须同是静态才行,你这样调用,非静态变量不能初始化
必须同是静态才行,你这样调用,非静态变量不能初始化
必须同是静态才行,你这样调用,非静态变量不能初始化
静态变量只能引用静态变量,