Reputation: 1032
I have the following method in java which reads a file of numbers (tab separated) and puts the numbers in a vector of Doubles
public static Vector<Double> getData(String path,int dataNum) throws Exception
{
File file = new File(path);
Scanner scan = new Scanner(file);
scan.useDelimiter("\t");
Vector<Double> content = new Vector<Double>();
int limit = 0;
while(scan.hasNext() && limit < dataNum)
{
content.add(Double.parseDouble(scan.next()));
limit++;
}
return content;
}
This is my sample file
0 20000 -9.2149 1.6078 4.1023 0.0089185 0.0057066 0.015156
However, when i run the code, I get the following error
Exception in thread "main" java.lang.NumberFormatException: For input string: "0
0"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at midterm.main.getData(main.java:91)
at midterm.main.main(main.java:123)
I believe my mistake is that I am parsing double but my file contains 0 and 2000 and that java sees them as integer. But EVEN if they are integers, i want them to be treated as Doubles and still go into my vector.
Upvotes: 1
Views: 1223
Reputation: 726569
This is not the entire content of my file. It's a file of 165 MB. MANY lines. but each line, the numbers are tab separated.
The problem is with the delimiter then: you need to allow \n
to be a delimiter as well:
scan.useDelimiter("[\t\n]");
Otherwise, the last number of the first line and the first number from the second line would be bunched together into a single string that looks like this: "0\n0"
and prints like two zeros on different lines, matching the error message that you get.
Upvotes: 3
Reputation: 53598
Instead of a scanner, just read the entire line in, split it on "\t" and then run through the resulting String[] with a "for-each" style for loop?
import java.util.*;
public class Test {
public static void main(String[] args) {
String input = "0\t20000\t-9.2149\t1.6078\t4.1023\t0.0089185\t0.0057066\t0.015156";
String[] columns = input.split("\t");
Vector<Double> dv = new Vector<Double>();
for(String s: columns) {
dv.add(Double.parseDouble(s));
}
System.out.println(dv.toString());
}
}
Output:
[0.0, 20000.0, -9.2149, 1.6078, 4.1023, 0.0089185, 0.0057066, 0.015156]
Upvotes: 0