Maybe there is a method that does this that I don’t know about – I doubt it though – but I’m trying to convert an array of strings to an array of Objects. Here is the problem: I’m reading a file in from the command line. The file represents several classes of the following types each with their own data fields. Vehicle is the parent class of all who follow: Vehicle,Car,American Car, Foreign car, Truck, Bicycle.
I have no problem reading the file into a string array. However I need to create objects of all these types and store them in an array of type Vehicle[]. For example a portion of the file looks like this:
- Vehicle
- Kim Stanley Robinson
- 2344 court drive
- (221)885-7777
- stackoverflow@overflow.com
- American Car
- John Bunyon
- 1010 binary lane
- (221)885-55643
- bgt.com
- convertable
- made in detroit
- union plant
Where Class type is the first line followed by, Owner’s Name, address, phone number, email address…Each type has fields particular to it. So a foreign car is not made in Detroit. Each of these fields appear on a separate line in the file. So what I’ve done is read the entire file into a string array. However, I need to find my types in the array of strings,create objects of those types, and store them in a Vehicle array. My main problem is that each data field is on a separate line. How should I approach this problem? This is java code by the way.
Initially reading the data into a String array is fine. Then you need to loop through that array, and based on the ‘first line’ of each loop (‘Vehicle’, ‘American car’ etc) you will know how many subsequent elements of the array belong to the same.
Something like this (i’ll let you fill in the blanks yourself):