[英]Using a scanner and split and storing the data in an array
我有一段代碼,必須掃描文件中的文本並將其存儲在字符串數組中。 我的代碼看起來像這樣
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
Stan:Slimy:Sales:10000.00:332
貝蒂:大桶:設計:12.50:50:244
如何使它掃描一行存儲在數組中,然后對6或5個參數使用addEmployee方法,然后繼續進行下一行。 文本有時有5個東西,並且由於有5個,secondParam或rowData [4]應該為0。
您設置
rowData[4] = null;
然后在解析之后
secondParam = Integer.parseInt(rowData[4]);
你會從中得到numberformatexception;
只需將其設置為0:
rowData[4] = "0";
您還檢查了長度是否為5,但是添加了第五個索引(即數組中的第六個字符串)。這將導致空指針異常。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.