Reputation: 186
so I'm learning Java for the first time. The following code throws a NullPointer
exception when square.toString()
is called in another class (where square is an instance of the object defined in this class), and I'm a little foggy about why this doesn't work. Can someone explain that to me?
public class SquareBuilder {
String box;
String[] parts;
final private String beam = "----";
final private String collumn = "|";
private int size;
public SquareBuilder(int firstSize)
{
size = firstSize;
}
public static String repeatString(String s, int n)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
{
sb.append(s);
}
return sb.toString();
}
public void changeSize(int newSize)
{
size = newSize;
}
public String toString( )
{
parts[0] = repeatString(beam,size) + "\n";
parts[1] = collumn + repeatString(" ",4*size-2) + collumn + "\n";
box = parts[0] + repeatString(parts[1],size-2) + parts[0];
return box;
}
}
Upvotes: 1
Views: 308
Reputation: 4891
A NullPointerException comes when you attempt to use methods on a null object. You should, in your constructor, initialize the parts
array using the expression
parts = new String[whateverSizeYouWant];
It is not clear to me what you are doing with the array.
Upvotes: 0
Reputation: 46408
Your question is not framed properly, however i guess that you are getting an NPE in your toString() method. Reason is you never really initialized your array String[] parts;
in your code.
You have to initialize it first:
public SquareBuilder(int firstSize)
{
size = firstSize;
this.parts = new int[give the size here];
}
Upvotes: 1
Reputation: 1500375
It's unclear why you've declared an instance variable called parts
which you then dereference (parts[0] = ...
) in toString()
- but you're never initializing it, so the value is null
... hence the exception.
Why is your implementation not just:
public String toString( )
{
String ends = repeatString(beam,size) + "\n";
String middle = collumn + repeatString(" ",4*size-2) + collumn + "\n";
return ends + middle + ends;
}
It's very unusual to want to modify an object in toString()
.
Upvotes: 3