读取csv文件时扫描器的NoSuchElementException

时间:2018-04-16 17:10:45

标签: java csv

所以我一直在尝试读取和解析CSV文件中的数据,并且我从文件中获得了所需的数据,但是当我打印它时,它让我真的很麻烦让我告诉你。

以下是我正在阅读的CSV文件

Liverpool Lime Street,P,B,D
Edge Hill,P,-,D
Mossley Hill,-,-,-
West Allerton,P,-,D
Liverpool South Parkway,-,-,D
Hunts Cross,P,-,-
Halewood,-,-,D
Hough Green ,-,-,D
Widnes ,P,B,-
Sankey for Penketh ,-,-,-
Warrington Central ,-,-,D
Padgate ,P,-,-
Birchwood ,-,-,D
Glazebrook,P,-,-
Irlam,-,B,-
Flixton,-,B,D
Chassen Road,P,-,D
Urmston ,P,B,D
Humphrey Park ,P,-,-
Trafford Park ,-,B,-
Deansgate ,P,-,D
Manchester Oxford Road ,-,B,D
Manchester Piccadilly ,P,-,D

这是我编写的用于在控制台中解析和显示的Java代码

facilities.useDelimiter(",");
    while(facilities.hasNextLine()){
        String name = facilities.next();
        String parking = facilities.next(); 
        String bike = facilities.next();
        String disability = facilities.next();
        System.out.print("Name: " + name + " ");
        System.out.print("Parking: " + parking + " ");
        System.out.print("Bikes: " + bike + " ");
        System.out.print("disability: " + disability + " ");
        System.out.println();
   }

这是结果的片段;问题出在哪里......

Name: Liverpool Lime Street Parking: P Bikes: B disability: D
 Edge Hill 
 Name: P Parking: - Bikes: D
 Mossley Hill disability: - 
 Name: - Parking: -
 West Allerton Bikes: P disability: - 
 Name: D
 Liverpool South Parkway Parking: - Bikes: - disability: D
 Hunts Cross

输出应该打印名称停车和残疾,然后打印一个具有相同数据的新行,但是如果你看上面的数据是遍布整个地方并且格式不正确。为什么在我从不告诉它时,facility.next()只是转到下一行?任何帮助表示赞赏

2 个答案:

答案 0 :(得分:1)

在您提供的代码中,您不会在每行输入结尾处考虑换行符。我建议,在通过添加disability

读取facilities.nextLine();之后尝试跳过其余部分(换行符)
facilities.useDelimiter(",");
while(facilities.hasNextLine()){
    String name = facilities.next();
    String parking = facilities.next(); 
    String bike = facilities.next();
    facilities.nextLine();
    String disability = facilities.next();
    System.out.print("Name: " + name + " ");
    System.out.print("Parking: " + parking + " ");
    System.out.print("Bikes: " + bike + " ");
    System.out.print("disability: " + disability + " ");
    System.out.println();
}

答案 1 :(得分:0)

正在发生的事情是,字段会被读取到下一个,,即使这是在下一行。因此,对于第一个disability,您将获得字符串:

D\n
Edge Hill

依此类推其他数据。

鉴于您检查是否存在“下一行”,您不会强制解析器关闭当前行末尾的字段。

所以要修复它,数据应该按行每行处理,或者你可以告诉解析器使用\n作为行分隔符。