-2

This is what I have so far, but I keep getting a NullPointException error.

public class Array
{
    
    private int[] val;

    public Array()
    {
        for (int i = 0; i < val.length; i++){
           if (i < 4) {
               System.out.print(",");
           }
           int[] val = new int[i];
        }
    }
cbjdfall
  • 7
  • 2
  • You are creating a local variable inside the constructor (int[] val = new int[i]) instead of using the instance variable (private int[] val). Try changing it to: val = new int[i]; This way you are referring to the instance variable instead of the local variable created after the if clause. – leogtzr Nov 15 '22 at 05:58
  • I feel that the duplicate is way above the level required to explained the basics to this OP and should be re-opened. @pradeep-simha – Scary Wombat Nov 15 '22 at 05:58
  • @leogtzr making this change still produces the same error... – cbjdfall Nov 15 '22 at 06:01
  • @cbjdfall, you cannot use the .length property yet in the for loop, because the array hasn't been initialized, you need to initialize it first and then use it. ``` public Array() { this.val = new int[5]; for (int i = 0; i < val.length; i++){ if (i < 4) { System.out.print(","); } // ... } } ``` – leogtzr Nov 15 '22 at 06:04

1 Answers1

0

A proper way to do this is

public class MyArray
{
    
    private int[] val;

    public MyArray()
    {
        val = new int [5];  // create an array of 5, all zero values at this stage
        for (int i = 0; i < val.length; i++){
               val [i] = i + 1;
        }
    }
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64