好急啊!谁能帮我写一下这程序阿???感激不尽阿!!!

kikigu1005 2007-06-14 03:13:42
write a program that will take numbers from a file called Numbers.txt and then add them up, and give out their average
...全文
178 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
应该改写成 File file = new File("C:/number.txt"); 应用“/”或“\\”都可以。
也可以不用写这句。

  br = new BufferedReader(new FileReader(file));
改为:
  br = new BufferedReader(new FileReader("c:/number.txt"));
也是一样的。
kikigu1005 2007-06-14
  • 打赏
  • 举报
回复
额``为什么读取不到文本文件。。
我把文本文件放在C盘
File file = new File("number.txt");是不是该写成File file = new File("C:\number.txt"); ?

  • 打赏
  • 举报
回复
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadNumber {

  public static void main(String[] args) {
    
    File file = new File("number.txt");
    BufferedReader br = null;
    try {
      br = new BufferedReader(new FileReader(file));
      String temp;
      float sum = 0;
      int i = 0;
      while( (temp = br.readLine()) != null) {
        sum += Float.parseFloat(temp);
        i++;
      }
      System.out.printf("平均值为:%.2f%n", sum / i);      
    } catch (FileNotFoundException e) {      
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        br.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

number.txt内容:
14.3
15.7
38.9
145.9

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧