gpt4 book ai didi

java - 我收到 java.lang.NullPointerException : null error and I don't know what is missing

转载 作者:行者123 更新时间:2023-12-02 04:07:41 24 4
gpt4 key购买 nike

 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)

最佳答案

您必须初始化employees 数组。读入员 worker 数后,执行 employees = new boolean[numEmp];(在 int numEmp = APIO.getInt(); 行之后)。否则,它为 null,因此尝试访问 employees[i] 会抛出 NullPointerException

关于java - 我收到 java.lang.NullPointerException : null error and I don't know what is missing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34099021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com