I have a problem where I am asked to read the tokens from a file and print out three values: the number of tokens that are numbers ( doubles), the number of tokens that are not numbers, and the sum of the numbers. and just those values.
I've managed to read the text file, and have been able to separate them based on them being doubles or not, but I am having trouble structuring my output which at the moment is just the list as is except that the non-doubles are listed as such where my text file is:
1 2 3 one two three
z 1.1 zz 2.2 zzz 3.3 zzzz
And my code looks like:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Lab1 {
public static void main(String[] args) {
Scanner in = null;
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException e) {
System.err.println("failed to open data.txt");
System.exit(1);
}
/**
* parse file token by token
*/
while (in.hasNext()) {
String token = in.next();
// if it's a Double
try {
double d = Double.parseDouble(token);
System.out.println(+d);
continue;
}
catch (NumberFormatException e) {
// It's not a double:
System.out.println("Not a double");
}
}
}
}
And this is my output:
1.0
2.0
3.0
Not a double
Not a double
Not a double
Not a double
1.1
Not a double
2.2
Not a double
3.3
Not a double
When I want my output to be this:
6 7 12.6
Which corresponds to the number of doubles, number of non-doubles, and sum of doubles respectively.
If I am phrasing this wrong please forgive. Just looking to fix my output.
Thanks in advance!