我遇到一个问题,要求我从文件中读取标记并打印出三个值:数字标记的数量( double )、非数字标记的数量以及数字的总和.以及那些值(value)观。
我已经设法读取了文本文件,并且能够根据它们是否为 double 来将它们分开,但是我在构建我的输出时遇到了问题,目前它只是列表,除了非- 在我的文本文件所在的位置列出 double :
1 2 3 one two three
z 1.1 zz 2.2 zzz 3.3 zzzz
我的代码如下:
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");
}
}
}
}
这是我的输出:
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
当我希望我的输出是这样的时候:
6 7 12.6
分别对应 double 数、非 double 数、 double 数之和。
如果我措辞有误,请原谅。只是想修复我的输出。
提前致谢!
最佳答案
你需要
在
main
函数的顶部定义变量,以记住 double 的当前计数, 非 double ,以及 double 的总和。int doubles = 0; int nonDoubles = 0; double sumOfDoubles = 0.0;
每次从文件读取时添加到 double /非 double /总和
while (in.hasNext()) { String token = in.next(); try { // try to convert string to double double d = Double.parseDouble(token); doubles += 1; sumOfDoubles += d; } catch (NumberFormatException e) { // conversion failed - it's not a double nonDoubles += 1; } }
在
main
函数末尾打印总计数。请注意,%.1f
会截断到一位小数。System.out.printf("%d %d %.1f", doubles, nonDoubles, sumOfDoubles);
关于计算我的 double 和非 double 的 Java 扫描器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45928872/