我正在读取CSV文件,并使用文件中的值为文件中的每一行创建一个对象。然而,我得到了错误“InputMismatchException”,我发现这是因为编译器需要一个字符串,因为CSV中的值没有用空格分隔(逗号是作为行的一部分读取的)。
然而,scanner没有创建任何空格的替换方法,所以我是否可以正确地假设必须将文件中的行转换为字符串?这似乎是将行拆分为值的唯一其他方法。尽管如此,所有值都将是字符串,因此它们不适用于预期整数/双精度的构造函数参数。如果有任何困惑,请让我知道,因为我发现很难解释我遇到的问题。
这是我的代码:
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公司。