我仍然不知道為什么這個程序不計算并給出我認為會的結果。我正在嘗試使用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
提交
取消