Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
962 views
in Technique[技术] by (71.8m points)

java - Reading double values from a file

I'm trying to read some numbers (double) from a file and store them in an ArrayList and an array (yes, I need both) with the code below:

try {
    Scanner scan = new Scanner(file).useDelimiter("\s*\n");

    while(scan.hasNextDouble())
    {
        tmp.add(scan.nextDouble());
    }

    Double[][] tmp2 = new Double[tmp.size()/2][2];
    int tmp3 = 0;
    for(int i = 0; i < tmp.size()/2; i++)
    {
        for(int j = 0; j < 2; j++)
        {
            tmp2[i][j] = tmp.get(tmp3);
            tmp3++;
        }
    }

} catch (FileNotFoundException e1) {
    e1.printStackTrace();
}

}

The file I'm trying to read is:

0.0 0.0
0.023 0.023
0.05 0.05
0.2 0.2
0.5 0.5
0.8 0.8
0.950 0.950
0.977 0.977
1.0 1.0

But well my code doesn't work, the hasNextDouble() function doesn't find anything, what am I doing wrong?

EDIT: ok so I edited the source a bit (changed from Object[][] to Double[][]) and added inserting values into the array after they were inserted into the ArrayList, but it still doesn't work - the 'while' loop isn't executed a single time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I tried reducing the code down to only test the Scanner by itself. The following code works with your data file:

public static void main(String[] args) {
    Scanner scan;
    File file = new File("resources\scannertester\data.txt");
    try {
        scan = new Scanner(file);

        while(scan.hasNextDouble())
        {
            System.out.println( scan.nextDouble() );
        }

    } catch (FileNotFoundException e1) {
            e1.printStackTrace();
    }

}

I got the following (expected) output:

0.0
0.0
0.023
0.023
0.05
0.05
0.2
0.2
0.5
0.5
0.8
0.8
0.95
0.95
0.977
0.977
1.0
1.0

Try this to make sure you're referencing the correct file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...