【问题标题】:I'm still baffled as to why this program doesn't produce the result that i expect it would我仍然对为什么这个程序没有产生我期望的结果感到困惑
【发布时间】:2018-12-03 00:52:39
【问题描述】:

我仍然无法弄清楚为什么这个程序不计算并给出我认为的结果。

我正在尝试使用 PrintWriter 类的实例将用户在 for 循环中指定的几个浮点值写入用户命名为 Numbers.txt 的文本文件。

然后我创建了 Scanner 类的对象 inputFile 并使用 hasNext 方法在 while 循环中读取这些值,在其中计算它们并将结果分配给总变量;一个初始化为 0.0 的累加器。

尽管如此,总变量的值仍然是 0.0,而不是文件中那些浮点值的累加。

我是 Java 新手,尤其是一般的编程新手,所以请有人帮我找出问题所在以及如何修复它以获得所需的结果。

提前致谢!下面是我写的代码部分:

public class FileSum {
   public static void main(String[] args) throws IOException {
      double individualValues, total = 0.0; // total is an accumulator to store the sum of the values specified in Numbers.txt, thus it must be initialized to 0.0
      int numberOfValues;
    
      Scanner kb = new Scanner(System.in);
    
      System.out.print("enter the file name: ");
      String fileName = kb.nextLine();
    
      System.out.print("enter the number of floating-point values in the file: ");
      numberOfValues = kb.nextInt();
    
      PrintWriter outputFile = new PrintWriter(fileName);
    
      for(int i = 1; i <= numberOfValues; i++) {
          System.out.print("the floating-point value number " + i + ": ");
          individualValues = kb.nextDouble();
          outputFile.println(individualValues);
      }
    
      File file = new File(fileName);
      Scanner inputFile = new Scanner(file);
    
      while(inputFile.hasNext()) {
          individualValues = inputFile.nextDouble();
          total = total + individualValues;
      }
    
      inputFile.close();
      outputFile.close();
      kb.close();
    
      System.out.println("the total values in Numbers.txt: " + total);
  }}

这是程序输出:

输入文件名:Numbers.txt

输入文件中浮点值的个数:2

浮点数1:4.5

浮点数2:3.2

Numbers.txt 中的总值:0.0

【问题讨论】:

  • 您期望的输出是什么,实际输出是什么? (产生该输出的输入是什么?)
  • 嗨 Radiodef,我期望的输出是用户指定的浮点值的累积。因此,例如,如果提示用户输入 2 个值,分别为 4.5 和 3.2。那么 Numbers.txt 中累积的总值将是 7.7

标签: java java.util.scanner inputstream filewriter printwriter


【解决方案1】:

您似乎正在尝试从 System.in 读取一些值,将它们写入文件,然后读取该文件并添加数字。

但是,由于在程序结束之前您不会关闭正在写入的文件,因此您无法确定在读取文件时文件内容是否已刷新到文件中。所以你很可能 inputFile.hasNext() 总是返回 false

只需将代码中的outputFile.close(); 行向上移动,这样它就会在您在新文件上创建扫描仪之前发生,那么您应该很好! 该文件将被写入,然后您可以打开它进行阅读。

进一步解释 这是因为PrintWriter 在调用 println 时不会自动刷新它的输出。出于性能原因,它保留在缓冲区中。还有其他构造函数采用 autoFlush 布尔值。如果设置为 true,它将刷新您写入文件的值。通过调用 close,您将刷新任何等待写入的内容,然后将绑定在此打开文件上的所有资源放在前面。

【讨论】:

  • 是的,这正是我试图用这个程序做的。顺便说一句,非常感谢你,因为我按照你的建议做了,而且效果很好!我将 outputFile.close() 语句向上移动到代码中,因此它位于 for 循环和 File file = new File(fileName) 之间。您能否进一步向我解释为什么这种方法有效?不幸的是,我仍然对此感到很困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多