Michelle Ashwini
Michelle Ashwini

Reputation: 918

Creating objects from text file input

I'm still very new to java. I am trying to create an array of objects from a text file. The text file has a list of names, and using these names, I'm trying to create objects. This is the method I've created to create the objects from the text file input. It gives an error when compiled. I'm not sure where I've done wrong.

   public boolean createObjects(PersonNames2[] person) throws Exception
   {
       boolean found = false;
       int position = 0;
       if(canCreateObjects() == true)
       {
           for(int i = 0; i < persons.length && !found; i++)
           {
               if(persons[i] == null)
               {
                   position = i;
                   found = true;
               }
           }
           Scanner reader = new Scanner(file);
           while(reader.hasNext())
           {
               person[position] = new PersonNames2();
               position++;
           }
           reader.close();
           return true;
       }
       return false;
   }

Upvotes: 1

Views: 955

Answers (3)

Michelle Ashwini
Michelle Ashwini

Reputation: 918

I've managed to get this working. Thanks! Here is the working code.

    public static List<Person> loadPersons(String path) throws Exception
    {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        List<Person> persons = new ArrayList<Person>();

        while((line = reader.readLine()) != null)
        {
            System.out.println("Adding " +line);
            persons.add(new Person(line));
        }

        return persons; 
    }

Upvotes: 0

Karol Kr&#243;l
Karol Kr&#243;l

Reputation: 3530

If you are new in Java, than this tiny GitHub project could be a nice set of hints for you.

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122008

error: array dimension missing PersonNames person[] = new Person[];

That's clearly telling that you are failed to give the size of your array.

You need to write

PersonNames person[] = new Person[size]; // For ex : 10 or any X

Array's are fixed in size and you need to tell the size of it while declaring/initializing it self.

Update:

Since you are reading data from a file and no idea about the length of array, better to choose ArrayList instead of array. Size of the ArrayList increases over the time you add elements to it.

Upvotes: 2

Related Questions