简体   繁体   English

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

[英]Reading/Summing Numbers from a Text File Using Java

I feel like I've made a really simple mistake, but I can't figure out what it is. 我觉得我犯了一个非常简单的错误,但我无法弄清楚它是什么。 I know the program is reading the correct file, but every time I run the program it simply returns 0.0000 as the sum. 我知道程序正在读取正确的文件,但每次运行程序时它只返回0.0000作为总和。 What have I done wrong? 我做错了什么?

When constructing a Scanner object that will read from a file, you must create a File object and pass it to the Scanner class constructor, it has the following definition: 构造将从文件读取的Scanner对象时,必须创建File对象并将其传递给Scanner类构造函数,它具有以下定义:

public Scanner(File source)
        throws FileNotFoundException

You aren't actually creating a Scanner object on the file, you are creating a Scanner object that is reading the filename as its input, which of course cannot be interpreted as a double. 您实际上并没有在文件上创建Scanner对象,而是创建一个Scanner对象,该对象将文件名作为输入读取,当然不能将其解释为double。

Change this line: 改变这一行:

Scanner input = new Scanner(filename);

To this: 对此:

Scanner input = new Scanner( new File(filename) );

You're using the wrong Scanner Constructor, that is your's is reading from the String filename . 您正在使用错误的Scanner构造函数,即您正在读取String filename I tested this, 我测试了这个,

// 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();
  }

I got the output 我得到了输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM