簡體   English   中英

將文件分隔為ArrayList <ArrayList<Double> &gt;

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM