【发布时间】:2018-04-01 22:16:23
【问题描述】:
我正在读取 CSV 文件,并使用文件中的值为文件中的每一行创建一个对象。但是,我收到了错误“InputMismatchException”,我发现这是因为编译器需要一个字符串,因为 CSV 中的值没有用空格分隔(逗号作为行的一部分被读取)。
但是扫描仪没有创建任何空格的替换方法,所以我假设我必须将文件中的行转换为字符串是否正确?这似乎是将行拆分为值的唯一其他方法。尽管那时所有的值都是字符串,所以它们不适合期望整数/双精度的构造函数参数。如果其中有任何令人困惑的地方,请告诉我,因为我很难解释我遇到的问题。
这是我的代码:
package code;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Element {
public int number;
public String symbol;
public String name;
public int group;
public int period;
public double weight;
public Element(int number, String symbol, String name, int group, int period, double weight){
this.number = number;
this.symbol = symbol;
this.name = name;
this.group = group;
this.period = period;
this.weight = weight;
}
public String toString(){
return number + ", " + symbol + ", " + name + ", " + group + ", " + period + ", " + weight;
}
public static List<Element> readElements() throws FileNotFoundException{
Scanner reader = new Scanner(new File("C:\\Users\\Sean\\Desktop\\elements.csv"));
List<Element> list= new ArrayList<Element>();
reader.nextLine();
while (reader.hasNextLine()){
Element e = new Element(reader.nextInt(), reader.next(), reader.next(), reader.nextInt(), reader.nextInt(), reader.nextDouble());
list.add(e);
}
return list;
}
}
CSV 文件
Atomic Number,Symbol,Name,Group,Period,Atomic Weight
23,V,Vanadium,5,4,50.9415
54,Xe,Xenon,18,5,131.293
70,Yb,Ytterbium,3,6,173.045
所以我试图从 CSV 文件中获取值,例如"23" 将是第一个 int,并使用它在 while 循环中使用scanner.nextInt 创建一个对象。
【问题讨论】:
标签: java list csv io java.util.scanner