1

I am trying to read from a CSV file using the Scanner but I am getting an InputMismatchException when I try and read the last double and are there is more than one line in my CSV file. I think this is because it is reading \n as part of the double. How do I get it to ignore the line break?

CSV file

P1,25,30
P2,10,10

Java

public static ArrayList<MarkEntry> readCSV(File file) {
    ArrayList<MarkEntry> entries = new ArrayList<>();
    try
    {
        Scanner in = new Scanner(file).useDelimiter(",");
        while (in.hasNext())
        {
            String title = in.next();
            double mark = in.nextDouble();
            double outOf = in.nextDouble(); //Program Crashes here
            entries.add(new MarkEntry(title, mark, outOf));
        }
    } catch (FileNotFoundException e)
    {
        System.out.println("File: " + file + " not found");
    }

    return entries;
}
Pyram
  • 57
  • 6

2 Answers2

1

You can use multiple delimeters:

Scanner in = new Scanner(input).useDelimiter(",|\\r\\n");

Note: On Linux, the line ending is just \n, so you would use this code:

Scanner in = new Scanner(input).useDelimiter(",|\\n");
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

The error is caused by the fact that your scanner tries to read up to the next delimiter (,) or to the end of the string. The last token will include the newline, and converting that value to a double results in the error you see.

Trim the newline off before parsing with your scanner:

String input = "foo,bar,2.5\n";
Scanner in = new Scanner(input.trim()).useDelimiter(",");
System.out.println(in.next());
System.out.println(in.next());
System.out.println(in.nextDouble());
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156