亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我仍然對為什么該程序無法產生我期望的結果感到困惑

我仍然對為什么該程序無法產生我期望的結果感到困惑

開心每一天1111 2021-04-08 17:15:20
我仍然不知道為什么這個程序不計算并給出我認為會的結果。我正在嘗試使用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
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號