问题出在 CVSParser
类(class)。我需要读取 .CSV 文件,然后将其传递给 ArrayList<Club>
示例.csv
球队,W,D,L,GF,GA
阿森纳,24,7,7,68,41
阿斯顿维拉,10,8,20,39,61
...
俱乐部类(class)
public Club(String team, int w, int l, int d, int GF, int GA) {
...
}
CSVParser 类
public static ArrayList<Club> CSVParser(String file) throws IOException{
ArrayList<Club> Lists = new ArrayList<>();
try{
Scanner scanner = new Scanner(new FileReader(file));
scanner.nextLine();
while(scanner.hasNextLine()){
String line = scanner.nextLine();
//System.out.println(line);
/*will get ArrayIndexOutOfBoundsException: 0 error */
String[] splits = line.split(",");
Lists.add(new Club(splits[0], Integer.parseInt(splits[1]),Integer.parseInt(splits[2]),
Integer.parseInt(splits[3]), Integer.parseInt(splits[4]), Integer.parseInt(splits[5])));
}scanner.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
System.out.println(Lists);
return Lists;
最佳答案
首先,这才是扫描仪的正确使用方法
Scanner s = new Scanner(input).useDelimiter(",");
int w = s.nextInt());
否则,只需使用 BufferedReader
接下来,您的 csv 文件中有一个或多个空行,您应该在拆分之前检查行长度,例如:
if (line.trim().length() > 0) {
String[] splits = line.split(",");
}
关于java - 将csv文件读取到arraylist对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28989676/