I'm attempting to read data from a CSV file, then put each row into an object, then place the object inside an arraylists of objects. I seem to be getting an error on this line
int age = fileReader.nextInt();
Here is my full code
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testfileio;
import java.io.FileNotFoundException;
import java.io.File;
import java.util.Scanner;
/**
*
* @author gregf
*/
public class TestFIleIO {
/**
* @param args the command line arguments
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args)
throws FileNotFoundException {
Company jam = new Company();
File csv = new File("C:\\Users\\gregf\\Documents\\NetBeansProjects\\TestFIleIO\\employees.csv");
Scanner fileReader = new Scanner(csv);
fileReader.useDelimiter(",|\n");
//skips first row (column headers)
fileReader.nextLine();
while(fileReader.hasNext()) {
String name = fileReader.next();
int age = fileReader.nextInt();
fileReader.nextLine();
try {
jam.setEmployees(new Employee(name, age));
}
catch(Exception ex) {
System.out.println(ex);
}
}
System.out.println(jam);
}
}
Error
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at testfileio.TestFIleIO.main(TestFIleIO.java:50)
C:\Users\gregf\Documents\NetBeansProjects\TestFIleIO\nbproject\build-impl.xml:1328: The following error occurred while executing this line:
C:\Users\gregf\Documents\NetBeansProjects\TestFIleIO\nbproject\build-impl.xml:948: Java returned: 1
BUILD FAILED (total time: 0 seconds)
A few notes:
Employee is an object with the name: String and age: int data fields
Company is an object that contains an ArrayList of Employee type and has a toString method to print all the employees' names and ages.
Since I have to use this in a project, so I can't use any libraries.
If you have any idea how to solve this, please share, thanks a lot.