【问题标题】:How do I get the number of input values from a text file in Java SE?如何从 Java SE 中的文本文件中获取输入值的数量?
【发布时间】:2015-01-25 07:20:32
【问题描述】:

我是计算机科学专业的第一学期学生,学习 Python 和 Java。

主题:解释器从文本文件中提取输入并将它们加在一起,然后找到平均值。

我的部分很好,程序将它们全部加在一起(我使用的是双精度,x),我的问题是我想弄清楚如何让解释器计算存在的 x 值的实际数量在文本文件中。当然,我可以通过对它们进行计数并为用于查找平均值的除数输入一个固定值来轻松地将它们组合在一起,但我希望程序这样做,如果所述文本文件中有不同数量的 x 值,程序可以适应。

这是我关于 Stack Overflow 的第一个问题,所以我可能不像一些更有经验的程序员那样具体,但我渴望学习。我以前用 Python 编写过更复杂的程序,因为那是我们的主要语言(即使与经验丰富的程序员编写的程序相比,这些程序也相对简单)。 Java(你们很多人都知道)是强类型的,这是我用该语言编写的第一个真正的程序。

下面是我在 NetBeans 8.0.1 IDE 中的代码:

/*
Purpose: Read real numbers from a file and print to the console only those
numbers which are greater than the mean of the numbers in the file.
Author: Brent McDonald
Date: 26 November 2014
Class: CSC 200 - 001W
 */
package homework.pkg23.average;

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Homework23Average {

    public static void main(String[] args) {

        double MEAN;
        double x;
        double y = 0;
        Scanner inputStream = null;

        try {
            inputStream = new Scanner (new File ("RawData.txt"));
        }
        catch (FileNotFoundException e) {
            System.out.println ("File not found, program aborted:");
            System.exit (1);
        }
        while (inputStream.hasNextDouble ()) {
            x = inputStream.nextDouble ();
            y += x;
            System.out.println (x);
        }
        System.out.println ("This is the sum of all x values: " + y);

【问题讨论】:

  • 只需添加一个int 变量(称之为count 之类的东西),每次调用nextDouble() 时递增。

标签: java average mean


【解决方案1】:

只需计算双打的数量,然后在扫描完文件后计算出平均值。

int count = 0;
while (inputStream.hasNextDouble ()) {
        count ++;
        x = inputStream.nextDouble ();
        y += x;
        System.out.println (x);
}
// divide y by count for the mean

【讨论】:

    【解决方案2】:

    添加一个int count 变量,然后在您的while 循环中增加计数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      相关资源
      最近更新 更多