2012-03-19 24 views
0

我有一个带双精度列表的文本文件。该行的第一个值是x值,第二个值是y值。将双精度加载到arrayList中

103.0 274.0 
    133.0 383.0 
    342.0 250.0 
    204.0 126.0 
    177.0 357.0 
    ... 

如何读取这些值并将它们加载到数组列表中?

ArrayList<Point> store = new ArrayList<Point>(); 


        File file = fc.getSelectedFile(); 

       StringBuilder all = new StringBuilder(); 

       BufferedReader reader = new BufferedReader(new FileReader(file)); 
       String input = null; 
       while ((input = reader.readLine()) != null) 
       { 
       String a = all.append(input+"\n").toString(); 

       String[] hold = a.split(" "); 

       double x = Double.parseDouble(hold[0]); 
       int aa = (int)(x); 
       double y = Double.parseDouble(hold[1]); 
       int bb = (int)(y); 

       store.add(new Point(aa, bb)); 
       } 
+1

http://stackoverflow.com/questions/1855753/reading-文件双值 – 2012-03-19 05:09:43

+0

格式化您的代码时请多加小心(本论坛无法顺利处理标签,特别是在与空间混合使用时不能正常处理 - 如您所见:-) – kleopatra 2012-03-19 11:22:26

回答

1
1: Get an input stream of the file. 
2: read line by line using readLine() method 
3: split the string by SPACE using split() method of String class 
4: the String array you got has two elements now. 
5: Double.parseDouble(array[0]) and Double.parseDouble(array[1]) are value of x and y 
6: store these values into the corresponding values of Point object 
7: add that point object to ArrayList. 
8: Done 
+0

嗯,我对它有所了解一点点。我无法让它正常工作。往上看。 – chief 2012-03-19 05:58:32

+0

@chief它显示的问题是什么? – 2012-03-19 06:11:23

+0

线程“AWT-EventQueue-0”中的异常java.lang.NumberFormatException:对于输入字符串:“178.0 306.0”文件的第一行是:349.0 178.0,文件的第二行是:306.0 159.0 – chief 2012-03-19 06:14:13

0

您可以在Java中使用资源包。使用

1

java的扫描仪和nextDouble()

扫描器使用读取文件和 参数nextDouble()是读出的文件数据类型