"显示java.lang.NullPointerException#34;错误

时间:2013-12-03 15:27:14

标签: java nullpointerexception bluej

我收到错误“java.lang.NullPointerException”,BlueJ似乎无法告诉我错误的含义。下面是出现错误的代码:

public int getJobsWaiting()
{
    int count = 0;
    int i = 0;

    while (count < jobList.size())
    {
        Job temp = jobList.get(i);

        if(jobList.get(count).isCompleted() != true)
        {
            count = count + 1;
        }
        i = i + 1;
    }
    return count;
}

3 个答案:

答案 0 :(得分:2)

jobListjobList.get(count)null。如果您尝试在null上调用某个方法(在您的情况下为size()isCompleted()),那么您就会得到NullPointerException

答案 1 :(得分:1)

试试这个,代码更少,只有jobList可以为null

int count = 0;
for (Job tmpJob : jobList) {
  if (!tmpJob.isCompleted())
  count++;
}

return count;

答案 2 :(得分:0)

您的代码很难理解。永远不会使用变量温度?

这样,如果作业完成,则不执行count + 1而且while不会结束?

if(jobList.get(count).isCompleted() != true)
{
   count = count + 1;
}

检查这是否有帮助:

public int getJobsWaiting(List<Job> jobList) {
    int count = 0;
    for (int i = 0; i < jobList.size(); i++) {
        Job temp = jobList.get(i);
        if (temp != null && !temp.isCompleted()) {
            count++;
        }
    }
    return count;
}