【问题标题】:Reading in a number.txt file and finding averages读取 number.txt 文件并找到平均值
【发布时间】:2019-02-07 06:19:31
【问题描述】:

目前正在处理一项作业,我需要读入一个数字文件并显示数字的总数、偶数总数、奇数总数以及所有三个的平均值。我目前正在努力寻找偶数和奇数的平均值。我必须显示偶数的平均值和奇数的平均值。我通过使用 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

【问题讨论】:

  • 你有什么问题?
  • else oddNum++; evenSum += Integer.parseInt(nums);周围添加一些括号
  • 你的else 块应该有大括号来包围这两个语句。此外,您正在增加奇数块中偶数的总和。
  • 哇,好吧,谢谢大家,看起来只是这两个技术问题阻止了我获得所需的结果,感谢您的所有帮助@ernest_k
  • 刚刚也看到了,非常感谢@ScaryWombat

标签: java file-io average parseint


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多