So I'm trying to create a simple program that an object that has an Integer Array as it's member and a method toString() that prints out all the elements in the Array. The code look like this:
public final class IntegerArray {
private int a[];
IntegerArray(int a[])
{
for(int i=0; i<a.length; i++) this.a[i]=a[i];
}
public String toString()
{
String fin=new String();
fin+='[';
for(int i=0; i<a.length-1; i++)
{
fin+=a[i]+", ";
}
fin+=a[a.length-1];
fin+=']';
return fin;
}
}
public class IntegerArrayTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
Random random=new Random();
int[] a={1, 5, 3, 7};
IntegerArray A=new IntegerArray(a);
System.out.println(A.toString());
}
}
However when I run the program it gives me 2 errors. One in the constructor and another when I initialize an the object from the class:
Exception in thread "main" java.lang.NullPointerException
at main.IntegerArray.<init>(IntegerArray.java:9)
at main.IntegerArrayTester.main(IntegerArrayTester.java:14)
Can somebody please tell what's the problem and how can I fix it?
Thank you in advance!