【发布时间】:2014-06-12 18:05:24
【问题描述】:
我正在为我正在处理的任务编写一个简单的程序。但是,当我尝试将 ArrayList“员工”移到主方法之外时,出现错误“无法对非静态字段员工进行静态引用”。
有效的代码:
public class X{
public static void main(String[] args){
ArrayList<Employee> employees = new ArrayList<Employee>();
while(i<6){
int skill = generator.nextInt(5);
int id = generator.nextInt(100); //for this purpose we will never
Employee newFresher = new Employee(id, skill);
employees.add(newFresher);
System.out.println(newFresher);
i++;
}
}
public void getCallHandler(){
//CODE THAT REALLY NEEDS TO SEE THAT ARRAYLIST
}
}
引发错误“无法进行静态引用”的代码:
public class X{
ArrayList<Employee> employees = new ArrayList<Employee>();
public static void main(String[] args){
while(i<6){
int skill = generator.nextInt(5);
int id = generator.nextInt(100); //for this purpose we will never
Employee newFresher = new Employee(id, skill);
employees.add(newFresher);
System.out.println(newFresher);
i++;
}
}
public void getCallHandler(){
//CODE THAT REALLY NEEDS TO SEE THAT ARRAYLIST
}
}
我只是不知道是什么原因造成的。非常感谢您的帮助。
PS:忽略奇怪的缩进。它只是stackoverflow格式化它很奇怪。
【问题讨论】:
-
Search first。此代码不是唯一的。
-
格式问题是由于您使用制表符造成的。将您的代码转换为使用空格进行缩进,就可以了。
标签: java exception static-methods