简体   繁体   中英

Read doubles that extend in multiple lines of txt file

My requirement is to read a double array from a text file. It might seem trivial by apparently i'm having an error with the delimiters.

Example:

4

0.000000000000000, 0.000000000000000, 1.000000000000000, 1.000000000000000

where 4 is the length of the double array and the values below separated by commas and space.

Scanner es =  new Scanner(filename);    
int numberofValues = es.readInt();
double[] Vector = new double[numberofValues];
for (int k = 0; k < numberofKnotValues; k++)
{
    knotValueVector[k] = es.nextDouble();
}

So up to 15 double values can fit in one text line and I encounter no problem. But if the vector I am supposed to read has more values then the values are split in two or more lines like so:

0.000000000000000, 0.000000000000000, 0.000000000000000, 0.125000000000000, 0.250000000000000, 0.375000000000000, 0.500000000000000, 0.625000000000000, 0.750000000000000, 0.875000000000000, 1.000000000000000, 1.000000000000000, 1.000000000000000

The problem is after I read the last double of the line and a comma remains at the end. When I try to read the next double the an error occurs that it is not a double but space.

So far the delimiter (" , *" ) seem to be enough for reading the doubles of line, but I can't find one that fits for multiple lines despite the fact that I tried some like

",s*\\n"

",s*\\r"

but they do not seem to work. So some help will be appreciated!!

Since there's no comma between the first number ( 4 ) and the rest, but there's always whitespace, set delimiter to:

",?\\s+"

UPDATE

The pattern I gave seems to work fine, regardless of how many numbers are given per line, and whether a line ends with a comma or not:

String input = "13\r\n" +
               "\r\n" +
               "0.000000000000000, 0.000000000000000, 0.000000000000000, 0.125000000000000,\r\n" +
               "0.250000000000000, 0.375000000000000, 0.500000000000000, 0.625000000000000\r\n" +
               "0.750000000000000, 0.875000000000000, 1.000000000000000, 1.000000000000000,\r\n" +
               "1.000000000000000";
Scanner in = new Scanner(input);
in.useDelimiter(",?\\s+");
int count = in.nextInt();
double[] values = new double[count];
for (int i = 0; i < count; i++)
    values[i] = in.nextDouble();
System.out.println(Arrays.toString(values));

Output

[0.0, 0.0, 0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 1.0, 1.0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM