Reputation: 7
I am getting an error when trying to use a JFileChooser to scan a text file add it to an array and parse one of the strings to a double and two to integers. Does it have to do with the fact that the addEmployee method adds the six parameters to an arrayList? Here is the code...
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.next().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);
}
}
}
John:Smith:Manufacturing:6.75:120:444
Betty:White:Manager:1200.00:111
Stan:Slimy:Sales:10000.00:332
Betty:Boop:Design:12.50:50:244
Upvotes: 0
Views: 1368
Reputation: 31699
String[] rowData = new String[5]; // edited out of original post
rowData = scan.next().split(":");
The first statement allocates an array of 5 Strings
and sets them all to null
. The second statement just throws away the array you just allocated. The result of split
will return an array of however many items it finds, and then you assign rowData
, which is a reference to an array, to a reference to the new array. The old one gets garbage collected. So there's no guarantee that rowData
will have 5 elements after this assignment.
You'll have to decide what you want to do if the split
doesn't return enough array elements. You could use something like Arrays.copyOf
that could put the split
result into some of the rowData
elements while leaving the rest alone, but then the unassigned elements will still be null
, and you'll just get a NullPointerException
a few lines later. So you have some design decisions to make here.
More: You may want to consider using the Scanner
method nextLine()
instead of next()
. next()
will return just one token, which means it will stop at a space character, which means you will have problems if someone is named "Mary Beth" or something like that.
Upvotes: 0
Reputation: 400
You are trying to fetch empNum = Integer.parseInt(rowData[5]);
row data only having size 5 that means index 0-4, Thats why ArrayIndexOutOfBoundsException is getting
So Initialize String[] rowData = new String[6];
Upvotes: 1