Add initial code to read in a CSV file and convert to a Vehicle

master
DjBushido 2014-01-22 10:34:17 -05:00
parent bb31ffcfd9
commit 46b45f5cd3
2 changed files with 55 additions and 0 deletions

View File

@ -1,5 +1,13 @@
package edu.uncc.itcs4180.PartTwo;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/* Assignment: Homework 1
* File name: PartOne.java
* Group:
@ -11,6 +19,43 @@ public class PartTwo {
public static void main(String[] args) {
// Set up reading the actual data
String filename = "raw_data.csv";
List<Vehicle> vehicles;
// Read in all of our data
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
vehicles = new ArrayList<Vehicle>();
String line;
while ((line = reader.readLine()) != null)
vehicles.add(readVehicle(line));
} catch (FileNotFoundException e) {
System.out.println("Could not open file: " + filename);
return;
} catch (IOException e) {
System.out.println("Error reading the CSV file.");
return;
}
// If we've made it here, we have the final list of all our vehicles
}
private static Vehicle readVehicle(String line) {
String[] elements = line.split(",");
try {
return new Vehicle(Integer.parseInt(elements[0]), // Model Year
elements[1], // Manufacturer Name
elements[2], // Model Name
Integer.parseInt(elements[3]), // Horsepower
Integer.parseInt(elements[4]), // No. Cylinders
Integer.parseInt(elements[5])); // No. Gears
} catch (IndexOutOfBoundsException e) {
System.err.println("Improperly formatted CSV file.");
return null;
}
}
}

View File

@ -16,6 +16,16 @@ public class Vehicle {
private int noCylinders;
private int noGears;
public Vehicle(int modelYear, String manufacturerName, String modelName,
int horsePower, int noCylinders, int noGears) {
this.modelYear = modelYear;
this.manufacturerName = manufacturerName;
this.modelName = modelName;
this.horsePower = horsePower;
this.noCylinders = noCylinders;
this.noGears = noGears;
}
public int getModelYear() {
return modelYear;
}