3 Replies - 765 Views - Last Post: 05 March 2011 - 07:02 PM Rate Topic: -----

#1 Soccernut14   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 22-March 09

Struggling With Arrays

Posted 05 March 2011 - 05:09 PM

Hello all,
I am working through one of my programs and I am using a String[]. The problem I am having is that I keep throwing a NullPointerExecption. I feel like this should be an easy fix I just seem to have forgotten how to do it or just suck really bad with arrays. Here is the part where my troubles are, if you would like me to put the whole program just let me know.

int w;
String [] A;
public boolean Add(String a){
  if(w < A.length){          //Error occurs on this line
    A[w] = a;
    w++;
    System.out.println("Added");
    return true;
  }
  else if(w == A.length){
    System.out.println("Array is full");
    return false;
  }
		
  return true;	
}    




Thanks a bunch,

Is This A Good Question/Topic? 0
  • +

Replies To: Struggling With Arrays

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5537
  • View blog
  • Posts: 14,539
  • Joined: 18-April 07

Re: Struggling With Arrays

Posted 05 March 2011 - 05:33 PM

You have defined a variable to serve as a string array, you have not actually created the array. You create it with the new keyword and give it a size...

String[] A; //<--- A is defined to hold a string array, it is NOT pointing to an array yet.

A = new String[10]; //<--- A now points to an array of 10 strings. A can now be used as an array.



Until you actually create the array and tell it its size, A is just pointing to nothing. You can't use it yet to store string values. It is currently NULL.

This post has been edited by Martyr2: 06 March 2011 - 12:35 PM

Was This Post Helpful? 1
  • +
  • -

#3 natas666   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 02-March 11

Re: Struggling With Arrays

Posted 05 March 2011 - 05:43 PM

View PostSoccernut14, on 05 March 2011 - 05:09 PM, said:

int w;
String [] A;
public boolean Add(String a){
  if(w < A.length){          //Error occurs on this line
    A[w] = a;
    w++;
    System.out.println("Added");
    return true;
  }
  else if(w == A.length){
    System.out.println("Array is full");
    return false;
  }
		
  return true;	
}    





Right now the array size is nothing because you didn't declare it. You should have something along the lines of String[] array = new String[x]; Where x is the size of the array. Seems to be the only problem here.
Was This Post Helpful? 0
  • +
  • -

#4 Soccernut14   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 22-March 09

Re: Struggling With Arrays

Posted 05 March 2011 - 07:02 PM

Awesome, thank you very much
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1