我仍然不知道為什么這個(gè)程序不計(jì)算并給出我認(rèn)為會(huì)的結(jié)果。我正在嘗試使用PrintWriter類的實(shí)例將用戶在for循環(huán)中指定的幾個(gè)浮點(diǎn)值寫(xiě)入用戶命名為Numbers.txt的文本文件中。然后,我創(chuàng)建了Scanner類的一個(gè)對(duì)象inputFile,并使用hasNext方法在while循環(huán)中讀取這些值,在其中計(jì)算它們并將結(jié)果分配給total變量;一個(gè)初始化為0.0的累加器。但是,總變量的值仍為0.0,而不是文件中這些浮點(diǎn)值的累加。我是Java的新手,尤其是Java的新手,所以請(qǐng)有人幫我確定問(wèn)題出在哪里,以及如何修復(fù)它以獲得所需的結(jié)果。提前致謝!以下是我編寫(xiě)的代碼部分: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在文件中輸入浮點(diǎn)值的數(shù)量:2浮點(diǎn)值數(shù)字1:4.5浮點(diǎn)數(shù)2:3.2Numbers.txt中的總值:0.0
我仍然對(duì)為什么該程序無(wú)法產(chǎn)生我期望的結(jié)果感到困惑
開(kāi)心每一天1111
2021-04-08 17:15:20