-1

I am in dire need of assistance please. I have a class called Fields and I wish to create an Array of Field objects but when I execute the code below:

static Field[] theField;
static Scanner userInput = new Scanner(System.in);

static void createFields()
{

    System.out.print("Enter the number of fields required: ");
    int numFields = userInput.nextInt();

    theField = new Field[numFields];

    for (int i = 0; i < numFields; i++)
    {

        System.out.print("Enter a name for field " + (i + 1) + ": ");
        String name = userInput.nextLine();

        theField[i].setFieldName(name);

    }

}

Then I get the following output and error in the console:

Enter the number of fields required: 3
Enter a name for field 1: Exception in thread "main" java.lang.NullPointerException
    at TestChart.createFields(TestChart.java:44)
    at TestChart.main(TestChart.java:14)

Please can you guys help resolve the error. I have been trying since last night to no avail.

Jens
  • 67,715
  • 15
  • 98
  • 113
Vincent Vega
  • 51
  • 1
  • 5
  • Which line is `TestChart.java:44`? – Jens Mar 17 '15 at 13:23
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Raedwald Mar 17 '15 at 13:26
  • Line 44 was: theField[i].setFieldName(name); but this question has been resolved. I made a noob error and could not spot it in my code. Thanks again guys!!! – Vincent Vega Mar 17 '15 at 13:37

3 Answers3

0

theField = new Field[numFields] is just creating array but array is empty so theField[i].setFieldName(name); will generate null pointer exception. You need to have the array filled by Field objects.

hemant1900
  • 1,226
  • 8
  • 9
  • This was where I got confused and forgot to instantiate the Array elements for the fields. I forgot that with and array of objects you need to instantiate. I simply added the following line of code before setting the Field name and it worked. theField[i] = new Field(); – Vincent Vega Mar 17 '15 at 13:36
0

You've created the Field-array (theField = new Field[numFields];), but you haven't created the individual Fields yet. Let's say you have 3 items, then your array is as follows: theField = { null, null, null } resulting in a NullPointerException.

So, add this:

if(theField[i] == null)
{
    theField[i] = new Field();
}

Right before this line in your for-loop:

theField[i].setFieldName(name);
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
0

So, while you have an array of Fields, none of the Field objects have been instantiated. Put the line

Field[i] = new Field();

before you call

Field[i].setFieldName();
DHerls
  • 827
  • 9
  • 21
  • Thank you so much. This was such a noob error and the moment I saw this answer I immediately knew this was what I did wrong. Code works perfectly. – Vincent Vega Mar 17 '15 at 13:33