0

I have a class called Vehicle. It has four sub classes: Car, Motorcycle, Van and Pickup. Here are the declarations of each:

     //vehicle 
     String licenseNo = null;        
     int engineCap = 0;  
     int cc = 0;
     String brand = null;
     String model = null;
     int passengers = 0;
     double price = 0;

     //car
     String material = null;
     String paintType = null;
     String colorC = null;

     //motorcycle
     String mainColor = null;
     String seatColor = null;
     String seatMaterial = null;

     //van
     int luggageCap = 0;
     String colorV = null;

     //pickup
     int tonsCap = 0;
     int yearsUsed = 0;
     String tyreQuality = null;

Note: It's not the way i declared them in the actual classes. That how i initialized them in the method im trying to write.

Here is the rest of the method:

  FileReader fileReader = new FileReader(filename);
    BufferedReader in = new BufferedReader(fileReader);

    int count = 0;
    Scanner scan = new Scanner(in);
    while (scan.hasNext()) 
    {
        vehicledata[count++] = new Vehicle(scan.next(), scan.nextInt(), scan.nextInt(), scan.next(), scan.next() ,scan.nextInt(), scan.nextDouble());
    }

I have an array :

static Vehicle vehicledata[] = new Vehicle[50]; 

to hold the values from the file. The file looks something like this: Text file im reading from

I could read up the the values in a normal Vehicle class. But i need to separate the sub-classes, so that i can sort them by their types. (like: List of cars, list of vans)

I am at the:

vehicledata[count++] = new Vehicle(scan.next(), scan.nextInt(), scan.nextInt(), scan.next(), scan.next() ,scan.nextInt(), scan.nextDouble());

part.. and I don't how i can differentiate the cars and other stuff at this point. (From the file after the last attribute in vehicle, there will be the type of vehicle, followed by the attribute of that subclass)

Any clues as to how i can do that? An if condition? But how can i implement it inside the

vehicledata[count++] = new Vehicle(scan.next(), scan.nextInt(), scan.nextInt(), scan.next(), scan.next() ,scan.nextInt(), scan.nextDouble());` 
2
  • I'd make the file JSON. You can either map from that to Java objects, or just deal with the parsed JSON as Maps and Lists. Lots of tools available. Commented May 7, 2014 at 21:58
  • If you need to use the scanner class (which looks pretty inconvinient to me), then you have to assing the results to temp variables till you can make the decision: int i1 = scan.nextInt(); int i2=scan.nextInt(); String t = scan.nextString(); if ("Car".equals(t)) { v = new Car(i1,i2); } else if .... Commented May 7, 2014 at 23:01

3 Answers 3

1

You can put everything in a csv file, something like:

L1412,10,100,Nissan,Sedan

and create a static factory method to create the instance you want:

 public static Vehical createVehical(String line){
        String[] parts = line.split(",");
        String type = parts[parts.length -1]; //get the last column
        switch (type) {
                    case "Van":
                        return new Car(a, b, c,...);
                    case "Sedan":
                        return new Van(a, b, c...);
                    default:
                        return null;
                }
    }

For furture checking subclass, use

if(vehical instanceof Sedan){

}else if(vehical instanceof Van){

}else...

Or you can look into Java Generic Collections, it may help you to solve your problem, hope it helps

Sign up to request clarification or add additional context in comments.

3 Comments

Still trying to wrap my head around the csv. I did not understand the parts.length-1 .. could you elaborate that a lil bit?
@ShifaTsar Im trying to say make the input file in certain structure, like for each line "carColor, carPrice, carEngine,..., carType", always make the car type as the last column of the line, this help to figure out what subclass the car belongs to. If some column is not applicable, make it null or any default value you want
Looks like i just used that method. I just posted an answer with a similar way. Putting the vehicle type as first one. Thanks :)
0

You have several class that Inherits from Vehicle.
In your file, you must delineate type of your object then all of attribute like:

van
xxxx //licenseNo
xxxx //engineCap
xxxx //cc
xxxx //brand
xxxx //model
xxxx //passengers
xxxx //price
xxxx //luggageCap
xxxx //colorV 

Now you must declare FileReader, BufferedReader and Scanner...
Ok!
Now you have several way to read file and store in array that the easiest is:

Van[] arrVan = new Van[50];
Car[] arrCar = new Car[50];
//etc
while (scan.hasNext()) 
    {
        String str = scan.next();
        if(str == "van")
        {
           Van van = new Van();
           van.setlicenseNo(scan.next());
           van.setEngineCap(scan.next());
           //etc
           // add van to arrVan
        }
        else if(str == "car")
        {
           Car car = new Car();
           //etc
           //add car to arrCar
        }   
        //etc
    }

2 Comments

So u mean to say that i should declare each of attributes for the sub-classes separately? What is the point in creating child classes then? :/
No, when your class like Car extend from Vehicle, all attribute from Vehicle exist in Car and you must put that value in file. when read file you must put that value in a instance of Car for example again.
0

Thank you for your effort :) Managed to solve the issue i was having, by simply changing the format of the file

while (scan.hasNext()) 
    {
        if(scan.next().toLowerCase() == "car")
        {
            carsdata[count++] = new Car(scan.next(), scan.nextInt(), scan.nextInt(), scan.next(), scan.next() ,scan.nextInt(), scan.nextDouble(), scan.next(), scan.next(), scan.next());
        }
        else if(scan.next().toLowerCase() == "motorcycle")
        {
            motorcyclesdata[count++] = new Motorcycle(scan.next(), scan.nextInt(), scan.nextInt(), scan.next(), scan.next() ,scan.nextInt(), scan.nextDouble(),  scan.next(), scan.next(), scan.next());
        }
        else if(scan.next().toLowerCase() == "van")
        {
            vansdata[count++] = new Van(scan.next(), scan.nextInt(), scan.nextInt(), scan.next(), scan.next() ,scan.nextInt(), scan.nextDouble(), scan.nextInt(), scan.next());
        }
        else if(scan.next().toLowerCase() == "pickup")
        {
            pickupsdata[count++] = new Pickup(scan.next(), scan.nextInt(), scan.nextInt(), scan.next(), scan.next() ,scan.nextInt(), scan.nextDouble(), scan.nextInt(), scan.nextInt(), scan.next());
        }
    }

2 Comments

== is for reference equality, i think you may want to use a.equals(b) for comparing two strings value equality:)
Thanks :) Im still getting an inputmismatchexception... im hoping the rest of my code works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.