• 0

[Java] Print out Array


Question

public void PrintOutArray()

{

for (int i = 0; i < array.length; i++)

{

System.out.println(i + " " + array);

}

}

My error is Null Pointer Exception on the for line. Can anyone help?

Link to comment
Share on other sites

12 answers to this question

Recommended Posts

  • 0

That doesn't work either. I now have -

public void PrintOutArray(String array)

{

for (int i = 0; i < array.length; i++)

{

System.out.println(i + " " + array);

}

}

Error - cannot find symbol - variable length

Link to comment
Share on other sites

  • 0
That doesn't work either. I now have -

public void PrintOutArray(String array)

{

for (int i = 0; i < array.length; i++)

{

System.out.println(i + " " + array);

}

}

Error - cannot find symbol - variable length

The String 'array' is not an array. You are missing "()" at the end of length. "array.length()" will give you the length of the string.

Rob2687's method should work.

Link to comment
Share on other sites

  • 0

You should also be able to use this little snippet of code to print what is stored in the array.

System.out.println("The values contained in the array are: " + new String(array));

I would also recommend changing the name of the array to something more intuitive than 'array', makes it much more manageable when there are multiple arrays and it's always good to not pick up bad coding habits ;)

Link to comment
Share on other sites

  • 0
You should also be able to use this little snippet of code to print what is stored in the array.

System.out.println("The values contained in the array are: " + new String(array));

I would also recommend changing the name of the array to something more intuitive than 'array', makes it much more manageable when there are multiple arrays and it's always good to not pick up bad coding habits ;)

That isn't a valid argument for the String constructor...

Link to comment
Share on other sites

  • 0

Really? That's odd, mashed up some code the other day using that and got it printing out the contents of an array of characters.

EDIT

Just realised it's only a valid argument for a string constructor when the array is an array of characters. Sorry, learn something new everyday, thanks for pointing that out kjordan2001.

Link to comment
Share on other sites

  • 0
Really? That's odd, mashed up some code the other day using that and got it printing out the contents of an array of characters.

EDIT

Just realised it's only a valid argument for a string constructor when the array is an array of characters. Sorry, learn something new everyday, thanks for pointing that out kjordan2001.

Yeah, you can pass an array of bytes or an array of characters and it'll turn them into a concatenated String.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.