java - 读取 number.txt 文件并查找平均值

标签 java file-io average parseint

目前正在做一项作业,我需要读取一个数字文件并显示数字总数、偶数总数、奇数总数以及所有三个数的平均值。我目前正在努力寻找偶数和奇数的平均值。我必须显示偶数的平均值和奇数的平均值。我通过使用 parseInt 将我读入的数字字符串转换为整数来找到总平均值,这样我就可以计算平均值,但是当我尝试对偶数和奇数执行相同操作时,我无法让它工作

这是我当前的代码:

public class Homework1 {
  public static void main(String[] args) throws IOException {
  // reads file in
  File num = new File("numbers.txt");
  Scanner inputFile = new Scanner(num);
  // creates rounding object
  DecimalFormat rounding = new DecimalFormat("#.##");
  // neccesary variables
  int count = 0;
  double numbers =0;
  int evenNum =0;
  int oddNum =0;
  double avg;
  double evenAvg;
  double oddAvg;
  double sum = 0.0;
  double evenSum = 0.0;
  double oddSum = 0.0;

  // reads in numbers file until last line is read
  while(inputFile.hasNext())
  {
         String nums = inputFile.nextLine();
  // converts string to ints so numbers can be added
         sum += Integer.parseInt(nums);
  // converts string to ints to so odd/even nums can be distinguished
         numbers = Integer.parseInt(nums);
  // updates total number count
         count++;

  // separates evens from odds
  if(numbers % 2 == 0)
      {
         evenNum++;
         evenSum += Integer.parseInt(nums);
      }

      else
         oddNum++;
         evenSum += Integer.parseInt(nums);
   } 

   // calculates total num average
   avg = sum/count; 

  // evenAvg = 
 //  oddAvg =  

   // output of credentials and results

   System.out.println("There are " +count+ " numbers in the file"+"\n");
   System.out.println("There are " +evenNum+ " even numbers"+"\n");
   System.out.println("There are " +oddNum+ " odd numbers"+"\n");
   System.out.println("The total average value is " +rounding.format(avg)+"\n"); 
   System.out.println("The odd number average is " +rounding.format(evenAvg)+"\n");
   System.out.println("The even number average is " +rounding.format(oddAvg)+"\n");

}

输出:

There are 982 numbers in the file

There are 474 even numbers

There are 508 odd numbers

The total average value is 50362.43

最佳答案

好的,所以我更正了 if/else 语句并添加了括号,这解决了我遇到的问题

oddNum++;
         oddSum += Integer.parseInt(nums);

关于java - 读取 number.txt 文件并查找平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54567400/

相关文章:

java - 完成后,Mediaplayer不会在第一次单击时重新启动

java - 如何为复选框监听器切换正确的类?

python - f.seek() 和 f.tell() 读取文本文件的每一行

c++ - 子进程中的间歇性文件访问错误

java - 创建一个 DelegateForest 并以预先确定的顺序显示它

java - 在 list 和运行时允许读写权限后权限被拒绝

java - 使用 ActionListener 将文件读入 JTextArea

sql-server - 累计平均数

sql - 返回 SQL 中列的平均值

python - 使用 numpy.mean 或 numpy.average 平均二维 numpy.array