java - 使用 Java 从文本文件中读取/求和数字

标签 java sum

我觉得我犯了一个非常简单的错误,但我不知道它是什么。我知道程序正在读取正确的文件,但每次运行该程序时,它只是返回 0.0000 作为总和。我做错了什么?

最佳答案

您使用了错误的Scanner构造函数,即您正在从字符串 filename 中读取的构造函数。我测试过这个,

// Why void? Just return the sum
public double readFile(String filename) {     
  Scanner input = null;
  double sum = 0;
  try {
    input = new Scanner(new File(filename));
    while (input.hasNextDouble()) {
      sum += input.nextDouble();
    }
    // output results
    System.out.printf("The total sum of the "
        + "doubles in the input file is %f\n", sum);
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } finally {
    input.close();
  }

我得到了输出

The total sum of the doubles in the input file is -3.651000

关于java - 使用 Java 从文本文件中读取/求和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128069/

相关文章:

c - 使用递归求数字 + 和 - 的总和 (c)

java - Spring beans 执行范围

java - mixinproperties 的 JCR 查询

java - 与java8兼容的最低 hibernate 版本

python - Python 中的可变部分数组求和

php - 在 MySQL 中通过 UNION 连接求和并在 PHP 中使用 ECHO 显示

java - 如何同时对数字和名称进行排序

java - Google 馆藏供应商和查找

python - Python 3.6 sum() 是否有 `start=0` 关键字参数?

python - 创建一个函数来对方程的结果求和。请看,没那么简单?