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.
To read a double, supply scanf with a format string containing the conversion specification %lf (that's a lower case L, not a one), and include a double variable preceded by an ampersand as the second parameter.
The readDouble() method of DataInputStream class in Java is used to read eight input bytes and returns a double value. This method reads the next eight bytes from the input stream and interprets it into double type and returns. Specified By: This method is specified by readDouble() method of DataInput interface.
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.
I had the same problem (not working scanner) and the solution seems to be surprisingly easy. You just need to set a locale for it.
// use US locale to be able to identify doubles in the string
scanner.useLocale(Locale.US);
taken from here: http://www.tutorialspoint.com/java/util/scanner_nextdouble.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With