title: Java: creating an array of objects using a data file
body: <p>I have an issue with an code for class where I am supposed to read data from a file "data.txt" then create an array of People objects using the data from the file.</p>
  
  <pre><code>import java.io.*;
  import java.util.Scanner;
  import java.io.FileNotFoundException;
   public class PersonDemo
   {
     public PersonDemo() throws FileNotFoundException
     {
      Person[] people = new Person[10]; // creating Person object array
      int flag; // to identify whether person, student or instructor
      try{
          File f = new File("data.txt");
          Scanner in = new Scanner(f);
          for (int i = 0; i &lt; 10; i++)
          {
              while (in.hasNext())
              {
                  final String[] arr = in.next().split(" ");
  </code></pre>
  
  <p>// secondary array to hold elements read in from file NOT WORKING</p>
  
  <pre><code>                flag =  Integer.parseInt(arr[0]);
                  if (flag == 1)
                  {
                      people[i] = new Person(arr[1], Integer.parseInt(arr[2])); // creates Person
  </code></pre>
  
  <p>java.lang.ArrayIndexOutOfBoundsException: 1 --- this exception occurs during the above line of code and I am unsure as to why, I am not even sure if my code is correct.. just that it compiles.</p>
  
  <pre><code>                } else if (flag == 2)
                  {
                      people[i] = new Student(arr[1], Integer.parseInt(arr[2]), arr[3], arr[4]); // creates Student
  
                  } else if (flag == 3)
                  {
                      people[i] = new Instructor(arr[1], Integer.parseInt(arr[2]), Double.parseDouble(arr[3])); // creates Instructor
                  }
              }
          }
      }
      catch (FileNotFoundException e) {
          System.out.println("no file found"); // error catch
      }
  
      for (int z = 0; z &lt; 10; z++)
      {
          people[z].toString(); //print out the people
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>anyone have any insight as to how I can fix the exception and get the code to work?</p>
  
  <p>The data file is in style of;</p>
  
  <p>identifier -- name -- age -- studentID/salary -- major</p>
  
  <p>1   Larry   50</p>
  
  <p>2   Joe 20  12345   Computer_Science</p>
  
  <p>3   Sally   40  40000</p>
  
  <p>2   Smith   21  23231   Compuer_Security</p>
  
  <p>1   Mary    32</p>
  
  <p>3   Michael 49  80000</p>
  
  <p>2   Amy     23  34343   Information_Tech</p>
  
  <p>1   John    5</p>
  
  <p>3   Darren  54  99995   </p>