问题描述
我正在尝试从文件中读取一些数字(double)并将它们存储在ArrayList和数组中(是的,我需要两者),代码如下:
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
但是我的代码不起作用,hasNextDouble()函数找不到任何东西,我做错了什么?
But well my code doesn't work, the hasNextDouble() function doesn't find anything, what am I doing wrong?
编辑:确定所以我编辑了一点源(从Object [] []更改为Double [] [])并在插入ArrayList后将数值插入到数组中,但它仍然不起作用 - '虽然'循环不是一次执行。
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.
推荐答案
我尝试将代码缩减为仅测试扫描仪本身。以下代码适用于您的数据文件:
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.
这篇关于从文件中读取双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!