java NullPointerException when running the program - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

java NullPointerException when running the program

It is a Java program I wrote, with so far no compile error. But there is the NullPointerException message when running the program. How to solve the problem?

Exception in thread "main" java.lang.NullPointerException
at TaskSet$Task.access$000(TaskSet.java:75)
at TaskSet.getStartTime(TaskSet.java:72)
at TaskSet.minCompletionTime(TaskSet.java:47)
at TaskSetTest.main(TaskSetTest.java:11)
Press any key to continue . . .

Here my program

import java.lang.Math;

public class TaskSet
{
private final int MAX = 20;
private Task tasks[];
private int matrix[][];
private int num;

public TaskSet()
{
tasks = new Task[MAX];
matrix = new int[MAX][MAX];
num = 0;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
matrix[i][j] = 0;
}
}
}

public void addTask(int x)
{
tasks[num++] = new Task(x);
}

public void addTaskConstraint(int i, int j)
{
if (matrix[j][i] == 1)
{
tasks[i].startTime = -1;
tasks[j].startTime = -1;
return;
}
matrix[i][j] = 1;
getStartTime(i);
minCompletionTime();
}

public int minCompletionTime()
{
int time = 0;
for (int i = 0; i < MAX; i++)
{
if (getStartTime(i) == -1)
{
return -1;
}
time = Math.max(time, getStartTime(i) + tasks[i].time);
}
return time;
}

public int getStartTime(int i)
{
for (int j = 0; j < MAX; j++)
{
if (matrix[i][j] == 1 && tasks[j].startTime != -1)
{
for (int k = 0; k < MAX; k++)
{
if (matrix[j][k] == 1 && tasks[k].startTime != -1)
{
tasks[j].startTime = Math.max(tasks[j].startTime, tasks[k].startTime + tasks[k].time);
}
}
tasks[i].startTime = Math.max(tasks[i].startTime, tasks[j].startTime + tasks[j].time);
}
}
return tasks[i].startTime;
}

private static class Task
{
private int time;
private int startTime;

public Task(int x)
{
time = x;
startTime = 0;
}
}
}

public class TaskSetTest
{
public static void main(String[] args)
{
TaskSet tasks = new TaskSet();

tasks.addTask(8);
tasks.addTask(2);
tasks.addTask(5);

System.out.println(tasks.minCompletionTime());
tasks.addTaskConstraint(0, 2);
System.out.println(tasks.minCompletionTime());
tasks.addTaskConstraint(0, 1);
System.out.println(tasks.minCompletionTime());

System.out.println(tasks.getStartTime(0));
System.out.println(tasks.getStartTime(1));
System.out.println(tasks.getStartTime(2));

tasks.addTaskConstraint(1, 2);
System.out.println(tasks.minCompletionTime());
System.out.println(tasks.getStartTime(0));
System.out.println(tasks.getStartTime(1));
System.out.println(tasks.getStartTime(2));

tasks.addTaskConstraint(1, 0);
System.out.println(tasks.minCompletionTime());
System.out.println(tasks.getStartTime(0));
System.out.println(tasks.getStartTime(1));
System.out.println(tasks.getStartTime(2));
}
}
Sign In or Register to comment.