Java scanner read from csv using delimeter and ignore endline

The code:

public static void main(String[] args) throws Exception{
    Scanner scn = new Scanner(new File ("kektura.csv"));
    int kezd = 0;
    List <String> indul = new ArrayList<>();
    List <String> veg = new ArrayList<>();
    List <Double> hossz = new ArrayList<>();
    List <Integer> emel = new ArrayList<>();
    List <Integer> lejt = new ArrayList<>();
    List <Boolean> pecset = new ArrayList<>();
    kezd=scn.nextInt(); 
    scn.nextLine();
    while(scn.hasNextLine())
    {
        scn.useDelimiter(";");
        indul.add(scn.next());           
        veg.add(scn.next());            
        hossz.add(scn.nextDouble());           
        emel.add(scn.nextInt());            
        lejt.add(scn.nextInt());            
        if(scn.next()=="n")
        {
            pecset.add(Boolean.TRUE);             
        }
        else
        {
            pecset.add(Boolean.FALSE);             
        }
        scn.nextLine();
    }
    for(Object x : pecset)
    {
        System.out.println(x);
    }
    scn.close();
}

And the file (It's a csv file, it has more lines, but they are the same pattern):

192
Sumeg, vasutallomas;Sumeg, buszpalyaudvar;1,208;16;6;n
Sumeg, buszpalyaudvar;Mogyorosi-domb, geologiai bemutatohely;1,512;24;8;n
Mogyorosi-domb, geologiai bemutatohely;Sumegi bazaltbanya vasutallomas;1,576;13;43;n
Sumegi bazaltbanya vasutallomas;Sarvaly erdeszhaz, pecsetelohely;2,101;69;18;i

I have a problem with reading this. Read the first line, it's okay. But the second line isn't good, because (i think) the delimeter reads until the ( ; ) character, but in the end of the line, there's not a ( ; ) . The last line of the while, I wrote scn.nextLine to read the \n character, but it doesn't work. I know thats a possible way, to read the line, and split it, but it's a school project, and the teacher told us to find out another solution. Is there a way, to solve this?

1 answer

  • answered 2018-01-13 17:34 Izruo

    As your teacher wants you to find another solution, I propose to use a BufferedReader to read the file in single lines. For each line you can then use String#split() and finally convert the respective parts to the required type (Integer#parseInt() etc).

    However, as this is stated as a homework question, I will not provide a full example.