[英]Separate file into ArrayList<ArrayList<Double>>
我有一个表格中的文件:
2.3 2.5
1.4 4.5
....
NaN NaN
2.2 1.4
4.6 5.6
....
(2列双打偶尔都等于“NaN”)
基本上我想将两个列分成:
ArrayList<Double> x;
ArrayList<Double> y;
虽然列中的两个数字都不等于“NaN”,但我想将它们添加到数组x和y中。 当BufferedReader读取一行时:
NaN NaN
我想将ArrayList x和y添加到allX和allY。
ArrayList<ArrayList<Double>> allX;
ArrayList<ArrayList<Double>> allY;
然后我想开始一个新的ArrayList x和y并继续读取数据,直到我到达另一个NaN NaN线(我将重复上述过程)或文件结束。
所以最后我留下了两个ArrayLists的双精度数组,即x和y数据。
我想不出办法,做任何想法?
如果它有助于理解我的问题:文件数据是世界上每个国家边界的纬度和经度数据,每个国家用(lat,lon)=(NaN,NaN)分隔。 我需要将数据分成每个国家的ArrayList,这些国家都包含在父ArrayList中。
目前我有:
BufferedReader br = new BufferedReader(new FileReader(new File("file.txt")));
String line;
String[] data;
while((line=br.readLine())!=null){
data=line.split(" "); //A String array with x and y (could be x="NaN" y="NaN")
//How do I then process this?
}
只是为了给你一个主意。 我知道这不是世界上最好的代码,但它是给你足够的信息,以便你可以继续。 希望能帮助到你。 代码是自解释的,如果您发现任何困难,请告诉我。
public class MyMain1 {
private static final String CONSTANT = "NaN";
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("/Users/Desktop/xyz.txt"));
List<List<Double>> allX = new ArrayList<>();
List<List<Double>> allY = new ArrayList<>();
List<Double> x = new ArrayList<>();
List<Double> y = new ArrayList<>();
try {
for (String str = null; (str = br.readLine()) != null; ) {
String[] s = str.split(" ");
if (CONSTANT.equals(s[0])) {
allX.add(x);
allY.add(y);
x = new ArrayList<>();
y = new ArrayList<>();
} else {
x.add(Double.parseDouble(s[0]));
y.add(Double.parseDouble(s[1]));
}
}
if (x.size() > 0 && y.size() > 0) {
allX.add(x);
allY.add(y);
}
} finally {
br.close();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.