Чтение в файле number.txt и нахождение средних - PullRequest
0 голосов
/ 07 февраля 2019

в настоящее время работает над заданием, и мне нужно прочитать в файле чисел и отобразить общее количество чисел, общее четное число, общее нечетное число и средние значения всех трех.В настоящее время я изо всех сил пытаюсь найти среднее число четных и нечетных чисел.Я должен отобразить среднее число четных и среднее число нечетных чисел.Я нашел общее среднее с помощью 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

1 Ответ

0 голосов
/ 07 февраля 2019

хорошо, поэтому я исправил операторы if / else и добавил скобки, и это устранило проблему, с которой я столкнулся

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