我有一段代码必须扫描文件中的文本并将其存储在一个字符串数组中。我的代码看起来像这样
else if (e.getSource()==readButton){
JFileChooser fileChooser = new JFileChooser("src");
if (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
empFile=fileChooser.getSelectedFile();
}
Scanner scan = new Scanner("empFile");
while(scan.hasNext()){
String[] rowData = scan.nextLine().split(":");
if(rowData.length == 5){
rowData[4] = null;
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
else{
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
if (position2.equals("Manager")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else if(position2.equals("Sales")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else{
c.addEmployee(fName, lName, position2, firstParam, secondParam, empNum);
}
}
}
正在扫描的文本看起来像这样
约翰:史密斯:制造:6.75:120:444
贝:白色:管理器:1200.00:111
斯坦:粘糊糊:销售:10000.00:332
贝:布普:设计:12.50:50:244
如何使其扫描一行将其存储在数组中,然后使用addEmployee方法获取6或5个参数,然后转到下一行。文本有时有5个东西,因为有5个secondParam或rowData [4]应该是0。
答案 0 :(得分:0)
您设置了
rowData[4] = null;
然后解析后
secondParam = Integer.parseInt(rowData[4]);
你会得到numberformatexception;
只需将其设为0:
rowData[4] = "0";
你还检查了长度是否为5,但你添加了第5个索引,这是数组中的第6个字符串..它会导致空指针异常..只是把它拿出来
if(rowData.length == 5){
rowData[4] = "0";
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
}
更新:
Scanner scan = new Scanner("empFile");
while(scan.hasNext()){
String[] rowData = scan.nextLine().split(":");
if(rowData.length == 5){
rowData[4] = "0";
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
empNum = Integer.parseInt(rowData[4]);
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else{
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
c.addEmployee(fName, lName, position2, firstParam, secondParam, empNum);
}
}