Create a set of objects when the player reads a text file

advertisements

Using my Computer class my computer class in the last project,I am supposed to write a program in Java that reads a file of computer data name computers.txt, and creates an array of Computer objects and so far I have this.

package project5;
import java.util.Scanner;
import java.io.*;

public class Project5 {

public static void main(String[] args){

    String[][] compArray = new String[50][50];
    String line = ":";
    String [] temp;

    Scanner file =null;
    try
    {
     file = new Scanner(new File("computers.txt"));
    }
    catch(FileNotFoundException e)
    {
        System.out.println("Could not open file " + "computers.txt");
        System.exit(200);
    }

    int i = 0;
    while ((line = file.nextLine())!= null){
        temp = line.split(":");
        for (int j = 0; j<compArray[i].length; j++) {
            compArray[i][j] = temp[j];
        }
        i++;
    }

    System.out.println(compArray[0][0]);
    }

}

Now I get an error. I did

System.out.println(compArray[0][0]);

to see if it was working but i got that error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at project5.Project5.main(Project5.java:44)

the computers.txt file looks like this

Dell Computers Inc.:Inspiron 15 Touch:6:500:Intel Core i5:CD/DVD+-RW:Windows 8.1:649.99
Dell Computers Inc.:Inspiron 17:4:500:Intel Core i3:CD/DVD+-RW:Windows 7:549.99
Dell Computers Inc.:Alienware 18:16:1000:Intel Core i7:Dual Layer Blu-ray:Windows    7:2999.99
Acer Computers Inc.:Aspire AT3-600:6:2000:Intel Core i5:BlueRay:Windows 8:599.99

I need help with creating an array when reading the file


You already have a Computer class (the one you linked to) that can hold all of these properties for a given "computer".

You know that each line in your file represents an individual computer. Therefore, each line can be represented by a Computer (the one you linked to).

You know how to parse these lines into an array of strings with split(), and that each element in that split array corresponds precisely to one of the properties of a "computer". This means that each line of the file can produce a String[] where each element of that String[] represents one of the properties of a computer (e.g. manufacturer is compArray[0], model is compArray[1], etc.).

You also know that you already have dynamic arrays such as ArrayList<Computer> at your disposal.

Now it's just a matter of putting all this together:

  1. Read each line from the file. For each line:
  2. Split it as you are already doing.
  3. Construct a new Computer and copy the split tokens to the appropriate properties.
  4. Add that Computer to your dynamic List<Computer>.

Be sure to handle errors gracefully: What happens if you hit a blank line, or a line without the expected number of tokens in it?

You have all of the tools you need, so think about how you can put them together to solve the problem at hand.