1

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!

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

When MadProgrammer says "allocates space", it's like you've said, I'm going to build a house...here. And there's now a space, a lot, reserved for the house. It doesn't exist yet, though. It hasn't been built. In programming, it means there's a space for the variable, a physical location in memory, but it hasn't been created or "instantiated" yet. Nothing's been put in that space. people[j] = new Person() puts a Person object in that space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.