Kevin Knapp
Kevin Knapp

Reputation: 53

Incorrect Output from CSV File

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.ArrayList;


/**
 * Write a description of class ReadInCsv here.
 * 
 * @author (Kevin Knapp) 
 * @version (10-10-2013)
 */
public class ReadInCsv
{
   public static void main(String[] args)
   {
       String csvName = "Countries.csv";
       File csvFile = new File(csvName);
       ArrayList<String> nameList = new ArrayList<>();
       ArrayList<String> popList = new ArrayList<>();
       ArrayList<String> areaList = new ArrayList<>();
       ArrayList<String> gdpList = new ArrayList<>();
       ArrayList<String> litRateList = new ArrayList<>();




         try
         {
           Scanner in = new Scanner(csvFile).useDelimiter(",");



            while (in.hasNext())
          {

           String name = in.next();
           nameList.add(name);
           String pop = in.next();
           popList.add(pop);
           String area = in.next();
           areaList.add(area);
           String gdp = in.next();
           gdpList.add(gdp);
           String litRate = in.next();
           litRateList.add(litRate);

         }
           in.close();
           System.out.println(nameList);
           System.out.println(popList);
           System.out.println(areaList);
           System.out.println(gdpList);
           System.out.println(litRateList);

         } 
        catch (FileNotFoundException e)
         {
            e.printStackTrace();
         }


    }
}

So im trying to read from a csv file and as it goes through it should add each scanned instance into a array list (im going to reference each element from these lists at a later point), but my outputs show that as soon as it reads something and adds it, it skips to the next line before reading the next string, i need it to read straight across, not diagonally

im sure im just missing something very simple, I just began learning java about a week ago, thanks for the help

Upvotes: 0

Views: 689

Answers (1)

William Gaul
William Gaul

Reputation: 3181

A big problem with this method is that unless each line in the file ends in a comma, newlines will not be delimited. A better way is to read each line in, split on commas, and add the values to the ArrayLists one line at a time:

Scanner in = new Scanner(csvFile);
while (in.hasNextLine()) {
    String[] fields = in.nextLine().split(",");
    if (fields.length == 5) {
        nameList.add(fields[0]);
        popList.add(fields[1]);
        areaList.add(fields[2]);
        gdpList.add(fields[3]);
        litRateList.add(fields[4]);
    } else {
        // Bad line...do what you want to show error here
    }
}

An even better way is to use a Java library dedicated to reading CSV files. A quick Google search should turn up some good ones.

Upvotes: 1

Related Questions