-1

Using this code

System.out.println("New Mark Entry\n--------------" + "\n\nEnter the description (up to 40 characters will be displayed):");
name = TextIO.getlnString();
if (name.length() > 40) {
    name = name.substring(0,40);
}
System.out.println("What was the assignment out of?");
totalMark = TextIO.getlnDouble();
System.out.println("What was the students mark?");
mark = TextIO.getlnDouble();
System.out.println("What was the weight of this assignement?");
weight = TextIO.getlnDouble();
input = 1;
int openSpot = 0;
for(int i = 0; i < markbook.length; i++) {
    if(markbook[i].getAssignment(name) == null) {   // java.lang.NullPointerException is thrown here
        openSpot = i;
        break;
    }

}
markbook[openSpot] = new Mark(name, totalMark, mark, weight);
break;

Causes a java.lang.NullPointerException to be thrown. Im a tad confused at what to do to fix this. If anyone could help or point me in the right direction it would be greatly appreicated

takendarkk
  • 3,347
  • 8
  • 25
  • 37
Jordan.McBride
  • 267
  • 2
  • 7
  • 20

3 Answers3

0

If the NPE happens on that exact line, the most likely cause is that markbook[i] is null. You don't show how you've initialised it, but in addition to allocating the array you also need to create the elements.

For an example, see https://stackoverflow.com/a/10044418/367273

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

I would look at the line where the NullPointerException has been throw.

Let say it is

markbook[i].getAssignment(name)

Then I would check that I actually set markbook[i] to something, because otherwise it will be null.

Note: this is not enough.

MyType[] markbook = new MyType[4];

as this is the same as

MyType[] markbook = { null, null, null, null };

If it still doesn't make sense, I would use a debugger to debug your code.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

you are initializing markbook after and trying to use it before

for(int i = 0; i < markbook.length; i++) {
        if(markbook[i].getAssignment(name) == null) {   // java.lang.NullPointerException is thrown here
            openSpot = i;
            break;
        }

    }
    markbook[openSpot] = new Mark(name, totalMark, mark, weight);//you are initializing markbook after and trying to use it before

it should be like following

//initialize first
markbook[openSpot] = new Mark(name, totalMark, mark, weight);

//use later
for(int i = 0; i < markbook.length; i++) {
        if(markbook[i].getAssignment(name) == null) {   // java.lang.NullPointerException is thrown here
            openSpot = i;
            break;
        }

    }
dev2d
  • 4,245
  • 3
  • 31
  • 54