views:

93

answers:

2
+1  Q: 

array of vehicles

is there anyone that can help me with java program I spent hour troubleshooting? I have no problem reading the file into a string array but I don't seem to know how to use switch or maybe if statement to store each line in an Array of Objects.

Write an application with a main that reads a file (from the command line) and fills an array of type vehicle[] with new vehicle (params), new car (params), new american car (params) new foreign car(params) , new truck (params), new bicycle (params), etc. depending on the first line that identifies each record. sample of data:

vehicle
eRob
Rob's house
(987) 654-3210
[email protected]

truck
aDougy
Doug's house
(123) 456-7890
[email protected]
30
61234.56
8/10/2003

bicycle
fTom
Tom's house
(246) 810-1214
[email protected]
7

If you see whats wrong with my code, please point at it:

public static void main( String[] args) throws Exception

{ 

  int traceOfArray = 100;

  Vehicle[] vehicle = new Vehicle[traceOfArray];

  File file = null;

  file = new File(args[0]);

  FileReader Fr = new FileReader(file); //read file.

  BufferedReader Br = new BufferedReader(Fr);

  String read = Br.readLine();

  try
  {

      while (read != null) 
      {

      char x = read.charAt(0);

      if(x=='v')

           vehicle[0] = new Vehicle(Br.readLine(), Br.readLine(), Br.readLine(), Br.readLine());

      else if(x=='c')

           vehicle[1] = new Car(Br.readLine(), Br.readLine(), Br.readLine(), Br.readLine(), Br.readLine(), Br.readLine());

     ...
A: 

You could also instead just give the BR object as argument to the class and let it figure out how many rows it needs:

e.g.

case 'v':
    new vehicle (Br)

...

Anders K.
+2  A: 

One thing is that ArrayLists are different than arrays.

arrayList(i++) = new vehicle (Br.readLine(), Br.readLine(), Br.readLine(),  Br.readLine());

should probably be

arrayList.add(new vehicle (Br.readLine(), Br.readLine(), Br.readLine(),  Br.readLine()));

If arrayList really is a vehicle[], then you need to use square brackets, not parenthesis:

arrayList[i++] = new vehicle (Br.readLine(), Br.readLine(), Br.readLine(),  Br.readLine());

Also, it's customary for class names to start with a capital letter (Vehicle, not vehicle)

bemace
ok none of this is working. i never worked with arrayList-s before. should I use if statement. should be less complicated than this switch statement
Ev_Angela
"not working" is pretty vague. What part isn't working? And how is your `arrayList` variable defined? Is it `ArrayList<vehicle> arrayList = new ArrayList<vehicle>()`, `vehicle[] arrayList = new vehicle[10]`, or something else?
bemace