简体   繁体   中英

Get an integer vector from a multi-line text file

I need to parse a .txt file to three double arrays. This files has various lines. In each line there are three integes divided by space.

Example:

19.1    24.3    0
18.2    24.0    0
12.6    24.9    20
14.4    28.0    20

My goal is to get three double array ( x , y and z ) and in each array there should be a column. So the result should be the same of writing the following instructions:

double[] x = {19.1,18.2,12.6,14.4};
double[] y = {24.3,24.0,24.9,28.0};
double[] z = {0,0,20,20};

I know how to open and read files, something like this:

String file = "filename.txt";
String line=null;
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(!(line=br.readLine()).contains("EOF")) {
  // read and process one line..
}

What I don't know how to do is how to parse each number of the current line and assign it to one of the three vectors.

You can simply split and parse each line as follows:

String[] row = line.split("\\s+");
double d1 = Double.parseDouble(row[0]);
double d2 = Double.parseDouble(row[1]);
double d3 = Double.parseDouble(row[2]);

Also, if the number of lines is not fixed then it will be easier and makes more sense to use ArrayList s of Double s instead of arrays of double s.

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