Hello,
I have a text file that is formatted as such:
Volkswagen, 547, 9.78, 2
Mercedes, 985, 45.77, 35
...
I am trying to figure out how use the Scanner to read from the text file and store the information into an ArrayList of objects.
ArrayList<Car> cars = new ArrayList<Car>();
I would then like to be able to use each element of the arraylist individually. For example:
cars.getName();
cars.getSerial();
...
Here is what I have so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerTest
{
public static void main(String[] args) {
ArrayList<Car> cars = new ArrayList<Car>();
File file = new File("car.csv");
try {
Scanner scanner = new Scanner(file).useDelimiter(",");
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
String name = scanner.next();
int serial = scanner.nextInt();
double itemCost = scanner.nextDouble();
int itemCode = scanner.nextInt();
System.out.println(name);
}//while
} //try
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
For some reason, I am getting a Mismatch input error and the items are not being added to an arraylist for proper usage. Is there a better method to using the file elements individually?
Any assitance will appreciated.
Thank you