I want to read a text file containing a sequence of number as below:
1.000000 1:-0.362772 2:-0.314085 3:-0.177185 4:0.898650 5:-0.154588
Currently, I'm reading the line and I use split()
method to split the number and store the numbers into an array. There are 3 variables will be used to store array elements, output
,number
, and value
.
1.000000
will be the output as an integer, [1, 2, 3, 4, 5]
will be an array of numbers, and [-0.362772,-0.314085,-0.177185,0.898650,-0.154588]
will be the array of values.
Here is my code:
while (line != null) {
double output = 0;
inputs = new double[6];
String[] inputPairs = line.split(" ");
output = Double.parseDouble(inputPairs[0]);
for (int i = 1; i < inputPairs.length; i++) {
int components = Integer.parseInt(inputPairs[i].split(":")[0]);
double data = Double.parseDouble(inputPairs[i].split(":")[1]);
inputs[components] = data;
}
outputs[counter] = (int) output;
input[counter] = inputs;
counter++;
line = br.readLine();
}
However, when I execute the code I got this exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at testReadFile.main(testReadFile.java:32)
.
I noticed that there is an extra space after the first index: 1.000000 1:-0.362772
being stored in the 2nd element of the array.
How do I remove the space? I have used trim()
but it doesn't work. Or is there a way to remove the array[2] which contains the space
?
String split
method accepts regex, so you can do this to split by multiple spaces
String[] inputPairs = line.split(" +");