我仍然不知道为什么这个程序不计算并给出我认为会的结果。我正在尝试使用PrintWriter类的实例将用户在for循环中指定的几个浮点值写入用户命名为Numbers.txt的文本文件中。然后,我创建了Scanner类的一个对象inputFile,并使用hasNext方法在while循环中读取这些值,在其中计算它们并将结果分配给total变量;一个初始化为0.0的累加器。但是,总变量的值仍为0.0,而不是文件中这些浮点值的累加。我是Java的新手,尤其是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.2Numbers.txt中的总值:0.0
添加回答
举报
0/150
提交
取消