【发布时间】: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