Reputation: 11
I am a beginner with java. I am trying to create the array of nested classes, and it would not work. In particularly it would not let me initialize array elements after allocation.
public class Salary {
class Person {
String name;
double salary;
void init (String n, double s) {
name = n;
salary = s;
}
}
public Salary (String args[]) { //the input is coming in pairs: name, salary
Person[] people; //creating the array
people = new Person[10]; //allocating 10 elements in array
int j = 0;
for (int i = 0; i < args.length; i+=2) {
people[j].init(args[i], Double.parseDouble(args[i+1])); //trying to initialize, and that is where it's giving me an error
System.out.format("%-15s %,10.2f%n",people[j].name, people[j].salary);
j++;
}
}
public static void main (String args[]) {
new Salary(args);
}
}
Thank you!
Upvotes: 1
Views: 162
Reputation: 347194
people = new Person[10];
only allocates space of 10
Person
objects, it does not create them.
You need to create an instance of the object and assign to a index within the array, for example
people[j] = new Person();
Try taking a look at Arrays for ore details
You should also consider using the objects constructor rather than an init
method
people[j] = new Person(args[i], Double.parseDouble(args[i+1]));
This will, of course, require you to supply a constructor.
Upvotes: 6