public void FillArray()
{
for (int i = 1; i < numEmp; i++)
{
employees[i] = true;
}
}
我认为这部分可能是我得到NullPointerException错误的原因,但我不知道我错过了什么。我已经为下面的程序提供了我的完整代码,以防万一有什么问题导致我发出错误信息。
//客户端类
public class Downsize
{
public static void main (String [] args)
{
System.out.print("Do you want to downsize the company? (Y/N): ");
String dummy = APIO.getString().toUpperCase();
while (dummy.equals("Y"))
{
Employee employee = new Employee();
System.out.print("Do you want to downsize the company? (Y/N):
dummy = APIO.getString().toUpperCase();
}
}
}
//对象类
public class Employee
{
int numEmp;
int sprayer;
int winner;
boolean [] employees;
public Employee()
{
System.out.print("How many employees? (0 to end): ");
int numEmp = APIO.getInt();
System.out.print("Who gets the spray can first?: ");
int sprayer = APIO.getInt();
FillArray();
Selection();
Winner();
}
public void FillArray()
{
for (int i = 1; i < numEmp; i++)
{
employees[i] = true;
}
}
public void Selection()
{
System.out.println("EM="); //debugging method
for (boolean em: employees)
{
System.out.println(em);
}
int complete = numEmp;
while (complete > 1)
{
System.out.print("spraycan passed to #" + sprayer);
if ((sprayer + 1) > numEmp)
{
sprayer = 0;
}
while (employees[sprayer + 1] == false)
{
sprayer++;
if (sprayer >= numEmp)
{
sprayer = 0;
}
}
employees[sprayer + 1] = false;
System.out.print(" - sprays #" + (sprayer + 1) + "'s hair");
complete--;
sprayer++;
while (employees[sprayer] == false)
{
sprayer++;
if (sprayer > numEmp)
{
sprayer = 1;
}
}
}
}
public void Winner()
{
if (sprayer == 0)
{
sprayer = 1;
System.out.print("\nThe Winner is #" + sprayer);
System.out.print("\n");
}
}
}
//错误消息的堆栈跟踪
java.lang.NullPointerException
at Employee.FillArray(Employee.java:22)
at Employee.<init>(Employee.java:14)
at Downsize.main(Downsize.java:9)
答案 0 :(得分:1)
您必须初始化employees
数组。读完员工人数后,执行employees = new boolean[numEmp];
(在int numEmp = APIO.getInt();
行之后)。否则,它为null,因此尝试访问employees[i]
会抛出NullPointerException
。
答案 1 :(得分:1)
我看到你们在@ mook的回答中喋喋不休,所以让我澄清一下,以便OP能够理解它而不是猜测。
class Example {
int size;
boolean[] array;
void initArray() {
size = 5;
array = new boolean[size];
}
}
在声明数组的大小及其类型后,您需要初始化数组。在上面的示例中,array
包含5个布尔值。
如果你写了
class Example {
int size;
boolean[] array = new boolean[size];;
void initArray() {
size = 5;
}
}
然后,由于默认情况下int
设置为0,即使您在代码中稍后更改用于声明大小的变量,array
的大小也将为0。这将给你一个错误,因为你将迭代到5。
@ mook的回答是正确的。