作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!