I'm currently stumped to how I can read from a text file whilst removing all whitespace. I have tried using the delimiter and string split to find no success. The problem is: my task requires me to read several lines of text from a text file and store it in an array.
However one of the lines has a visible 'gap' or several whitespaces (denoted by the speech marks here) which I assume is causing me problems.
Here is a sample of the text file:
jy1 10 10 10 10 10
mp1 6 5 6 " " 7 5
ls1 9 7 12 14 15
mp2 10 12 15 15 14
lb1 12 12 12 12 12
And here is my code:
try {
FileReader reader= new FileReader(attendancesFile.txt);
String line="";
Scanner in=new Scanner(reader);
// reading from file line by line
while (in.hasNextLine()) {
line=in.nextLine();
// splitting line read in separate words
String tokens[]=line.split(" ");
// creates an array of attendances
// using 5 separate attendances represented as integer values from file
String id= tokens [0];
int attend1= Integer.parseInt(tokens [1]);
int attend2= Integer.parseInt(tokens [2]);
int attend3= Integer.parseInt(tokens [3]);
int attend4= Integer.parseInt(tokens [4]);
int attend5= Integer.parseInt(tokens [5]);
int [] attend= {attend1, attend2, attend3, attend4, attend5};
// uses FP method to find Fitness Class with given ID
// sets the attendance for Fitness Class with given ID
fp.classByID(id).setAttendance(attend);
}
reader.close();
in.close();
}
catch (IOException e) {
System.err.println("Reading from file error.");
}
Ideally I should have 5 arrays, each of which stores the 5 integer numbers from each line of the file. I will then pass these arrays to another class where a method adds this array of int to an object array.
However, it gives me an error: Exception in thread "main" java.lang.NumberFormatException: For input string: "" which I assume is due to the white space being read and added to the array. I have tested to print out each array & it appears as though the fourth array only has 4 elements & a blank space.