Reputation: 1111
I have a homework problem to calculate delayed flights of different airplane carriers. I am reading from a CSV file and have create a class for "carriers" with total flights and delayed flights. Since there is many carriers (10 or so), how can I create carrier objects as they are read from the CSV (or a 2d array).
Instead of
carrier UA = new carrier("Us Airways", 100, 50);
carrier Delta = new carrier("Delta", 100, 50);
and hard coding all the objects.
right now the CSV data is in a 2D array, and the non object oriented code is as follows.
public static void main (String [] args) throws Exception{
CSVReader reader = new CSVReader(new FileReader("delayed.csv"));
String [] nextLine;
String[][] flightData = new String[221][3];
int i=0;
while ((nextLine = reader.readNext()) != null) {
for(int r = 0; r<2; r++){
flightData[i][0] = nextLine[1];
flightData[i][1] = nextLine[6];
flightData[i][2] = nextLine[7];
}
i++;
//System.out.println("Carrier: " + nextLine[1] + "\t\tTotal: " + nextLine[6] + "\t\tDelayed: " + nextLine[7] + "");
}
while(flightData != null){
carrier
}
}
thanks.
Upvotes: 0
Views: 306
Reputation: 19778
List<Carrier> listCarrier = new ArrayList<Carrier>();
while ((nextLine = reader.readNext()) != null) {
listCarrier.add(new Carrier(nextLine[1], Integer.valueOf(nextLine[6]), Integer.valueOf(nextLine[7])));
}
Note that the class Carrier should start with an uppercase.
If you want to avoid dupplicates, you can use HashMap instade of ArrayList as follows:
Map<String, Carrier> listCarrier = new HashMap<String, Carrier>();
In order to insert a new record, use:
Carrier carrier = new Carrier(nextLine[1], Integer.valueOf(nextLine[6]), Integer.valueOf(nextLine[7]));
listCarrier .put(nextLine[1],carrier );
//Here the key is the carrier name, and the value is the carrier object
If you have dupplicate carriers with same name but different values, only the last one will be kept in the HashMap.
To get a carrier from the list, use:
listCarrier.get("carrier_name")
And this would return the carrier with name "carrier_name" from the Map, if available.
Upvotes: 1