SRL Archive - Java Help and Tutorials

Help please :)


Shuttleu

2010-09-22 13:53:58

well i just started learning java again and i forgot nearly everything

anyway so far i have this
class First {
int x = 2;
}

public class Main {

public static void main(String[] args)
{
First[] testing = new First[5];

testing[2].x = 5;

System.out.println(testing[2].x);
}
}
it compiles fine but when i run it i get
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:11)


any ideas are welcome

~shut

Yakman

2010-09-28 12:54:54

change to this.


class First {
int x = 2;
}

public class Main {

public static void main(String[] args)
{
First[] testing = new First[5];
testing[2] = new First();
testing[2].x = 5;

System.out.println(testing[2].x);
}
}

Shuttleu

2010-09-28 13:56:22

From: Yakman
change to this.


class First {
int x = 2;
}

public class Main {

public static void main(String[] args)
{
First[] testing = new First[5];
testing[2] = new First();
testing[2].x = 5;

System.out.println(testing[2].x);
}
}


hmmm… ok, thanks :)

so if i was to create a array that had a length of 1000, then i would have to do that for each one?

if i do then i know i could obviously just use a loop

~shut

arash

2010-10-03 00:39:59

You should create a constructor for your inner class and using that constructor initialize your array. It is much simpler.