1

I am working on a project where I have a class named dBase with getter and setter methods for fields such as first and last names. However, When I run the code, line 6 of the code portion is highlighted with a java.lang.NullPointerException error, which doesn't help me at all.

How do I make this work? Thanks, in advance

case 3:
input.nextLine();
for (int i = 0; i < num; i++){
System.out.println("Enter first name of student " + (i + 1));
String firstN = input.nextLine();
roster[i].setfName(firstN);
System.out.println("Enter last name of student " + (i + 1));
String lastN = input.nextLine();
roster[i].setlName(lastN);
    }
        break;
noov101
  • 21
  • 2

2 Answers2

2

You didn't include the full source which means I just have to guess, but, usually, this is the problem:

When you write something like:

class MyThing {}

MyThing[] x = new MyThing[10];

what you're doing is creating an array that is capable of holding references to 10 myThings. It does not create 10 myThings. It doesn't create any MyThings at all, in fact. You still have to actually make them. For example:

for (int i = 0; i < x.length; i++) x[i] = new MyThing();

NOW you've created 10 mythings (that loop runs 10 times, each time, it makes a mything, that math works out).

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

I would say that your array String[] roster is not initialized correctly. If you do not know how many elements your array will contain, I would recommend using an ArrayList instead of a standard String array.

dice2289
  • 51
  • 3