Nivek
Nivek

Reputation: 17

Why is this returned array not working?

In this code I'm trying to pass a two dimensional array of chars into cArray and return a one dimensional array of elements that display a string of each row of the two dimensional array.

Example:

Input array (two dimensonal):

'a' 'b' 'c' 'd'

'e' 'f' 'g' 'h'

'i' 'j' 'k' 'l'

Returned array (one dimensional):

abcd

efgh

ijkl

Here is my code:

Main:

public class hw2p1
{   
   public static void main (String [] args) 
   {

  // declare and initialize array of chars
  char[][] array = { {'a', 'b', 'c', 'd'},
                     {'e', 'f', 'g', 'h'},
                     {'i', 'j', 'k', 'l'} };

  cArray array1 = new cArray(array); 

  String[] array2 = array1.getArray();

  for (int i=0; i<array2.length; i++) 
    System.out.println(i+" "+array2[i]);


  }
}

cArray:

public class cArray
{   

   private String[] newArray;

   public cArray ( char[][] array2 )
   {  
      String[] newArray = new String[array2.length];

      for (int i=0; i < array2.length; i++)
         newArray[i] = String.valueOf(array2[i]);

      for (int l=0; l < array2.length; l++)
         System.out.println(newArray[l]);



   }
   public String[] getArray()
   {
      return newArray;
   }
}

I get this error when I try to run this:

Exception in thread "main" java.lang.NullPointerException at hw2p1.main(hw2p1.java:16)

Sorry if this is an obvious error. I'm very new to programming. Thank you for any help!

Upvotes: 1

Views: 170

Answers (3)

sree999
sree999

Reputation: 1

In your cArray method, you are actually initializing a new local variable. Instead, you should use the instance variable.

Replace this:

String[] newArray = new String[array2.length];

with

newArray = new String[array2.length];

Also, it's always nice to do a null check:

if(array2!=null){
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500375

This is the problem:

String[] newArray = new String[array2.length];

That's declaring a local variable in the constructor - so you're not assigning a value to the field at all. You just want:

newArray = new String[array2.length];

Having said that, it's not clear why you need to create an instance for this at all - I'd be tempted to just have a single method with a signature of:

static String[] combineArrays(char[][] arrays)

Then you can use just a local variable, and there'll be no field to worry about at all. This could be in the same class as your main method, too.

Upvotes: 4

August
August

Reputation: 12558

Your local variable newArray is hiding the field newArray. Change this line:

String[] newArray = new String[array2.length];

to this:

newArray = new String[array2.length];

Upvotes: 2

Related Questions