我正处于一个与我一直在努力的任务的关键时刻。它是一个创建元素周期表的程序。要创建每个元素,我需要获取一个文件(CSV),将其拆分,并将每个拆分部分设置为一个名为" Element"的对象的属性。分割文件的每一行并将其读入到目前为止都没有问题。但是,我一直坚持如何获取每个部分并将其添加为Element对象的属性。任何人都可以对此有所了解吗?
这是我的代码:
"周期表" class:
public class PeriodicTable {
private String line;
private String[] parts;
private String filename = "file.csv";
public PeriodicTable() throws IOException {
}
public void readValues(String filename) throws IOException{
Scanner sc = new Scanner(new FileReader(filename));
ArrayList<Element> ar1 = new ArrayList<Element>();
while(sc.hasNextLine()){
line = sc.nextLine();
parts = line.split(",");
Element el = new Element();
el.setChemicalName(parts[0]);
el.setAtomNum(parts[1]);
el.setMeltPoint(parts[3]);
el.setBoilPoint(parts[4]);
el.setDensity(parts[5]);
el.setAtomWeight(parts[6]);
// System.out.println(el.getChemicalName());
//System.out.println(el.getAtomWeight());
ar1.add(el);
}
System.out.println(ar1);
}
}
&#34;元素&#34;类
public class Element {
private String chemicalName;
private String atomNum;
private String boilPoint;
private String meltPoint;
private String density;
private String atomWeight;
public Element() throws IOException{
}
/**
* @return the chemicalName
*/
public String getChemicalName() {
return chemicalName;
}
/**
* @param chemicalName the chemicalName to set
*/
public void setChemicalName(String chemicalName) {
this.chemicalName = chemicalName;
}
/**
* @return the atomNum
*/
public String getAtomNum() {
return atomNum;
}
/**
* @param atomNum the atomNum to set
*/
public void setAtomNum(String atomNum) {
this.atomNum = atomNum;
}
/**
* @return the boilPoint
*/
public String getBoilPoint() {
return boilPoint;
}
/**
* @param parts2 the boilPoint to set
*/
public void setBoilPoint(String parts2) {
this.boilPoint = parts2;
}
/**
* @return the meltPoint
*/
public String getMeltPoint() {
return meltPoint;
}
/**
* @param parts2 the meltPoint to set
*/
public void setMeltPoint(String parts2) {
this.meltPoint = parts2;
}
/**
* @return the density
*/
public String getDensity() {
return density;
}
/**
* @param density the density to set
*/
public void setDensity(String density) {
this.density = density;
}
/**
* @return the atomWeight
*/
public String getAtomWeight() {
return atomWeight;
}
/**
* @param input the atomWeight to set
*/
public void setAtomWeight(String input) {
this.atomWeight = input;
}
@Override
public String toString(){
return chemicalName;
}
}
因为String.split()
方法使用数组来保存拆分的每个部分,所以我尝试使用对包含该值的parts数组中的索引的引用来设置每个属性的值,例如.. ..
el.setChemicalName(parts[0]));
然而,这似乎并没有起作用 - 当我尝试打印出该变量的值时,我通常会得到一个空值。
答案 0 :(得分:0)
我建议您使用OpenCSV让您的生活更轻松。
答案 1 :(得分:0)
您的代码工作正常,但请
filename
,可能在调用方法readValues
时传递了错误的值。String.split
中,最好使用parts = line.split("\\,");
,因为拆分使用和正则表达式可以在String数组中进行分隔。