0

大家好,我在以下路径 C:/Users/Marc/Downloads/vector25 中有一个文本文件,其中包含以下格式的逗号分隔值

-6.08,70.93,-9.35,-86.09,-28.41,27.94,75.15,91.03,-84.21,97.84,-51.53,77.95,88.37,26.14,-23.58,-18.4,-4.62,46.52,-19.47,17.54, 85.33,52.53,27.97,10.73,-5.82,

我将如何阅读这个文本文件并将这些双精度数存储在一个数组中?

我目前正在考虑尝试使用缓冲阅读器,但到目前为止,我无法找到答案,谁能指出我正确的方向?

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Scanner;
    public class subvector {

public static void main(String[] args){

    FileReader file = null;
    try {
        file = new FileReader("C:/Users/Marc/Downloads/vector25");
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    ArrayList<Double> list = new ArrayList<Double>();
    int i=0;
    try {
        Scanner input = new Scanner(file);
        while(input.hasNext())
        {
           list.add(input.nextDouble());
           i++;
        }
        input.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
   for(double k:list){
       System.out.println(k);

   }
}
4

3 回答 3

3

Scanner.nextDouble()默认使用空格作为分隔符。您的输入有逗号作为分隔符。您应该input.useDelimiter(",")在调用之前使用将逗号设置为分隔符input.hasNext()。然后它应该按预期工作。

于 2013-09-23T12:01:54.320 回答
3

你应该使用分隔符

Scanner input = new Scanner(file);
input.useDelimeter(",");
于 2013-09-23T12:02:07.613 回答
0

我认为您的代码片段不适用于指定的数据,即 -6.08,70.93,-9.35,-86.09,-28.41,27.94,75.15,91.03,-84.21,97.84,-51.53,77.95,88.37,26.14,-23.58,- 18.4,-4.62,46.52,-19.47,17.54, 85.33,52.53,27.97,10.73,-5.82,

但是您的程序可以正常工作这些类型的数据:

19.60
63.0
635.00
896.63
47.25

我已经修改了你的程序并用你的数据进行了测试。它按预期工作。

public static void main(String[] args) {
    FileReader file = null;
    try {
        file = new FileReader("D:\\log4j\\vector25.txt");
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    ArrayList<Double> list = new ArrayList<Double>();
    int i=0;
    Double d= null;
    try {
        BufferedReader input = new BufferedReader(file);
        String s=null;
        while((s=input.readLine())!=null) {
            StringTokenizer st = new StringTokenizer(s,",");
            while(st.hasMoreTokens()) {
            try {
                d = Double.parseDouble(st.nextToken());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            list.add(i, d);
        }
    }
    input.close();
} catch(Exception e) {
    e.printStackTrace();
}
for(double k:list) {
    System.out.println(k);
}
}

请查看它,如果您更新任何内容,请告诉我。

这是我在 stackoverflow 上的第一篇文章。

谢谢,普拉萨德

于 2013-09-23T12:29:51.930 回答