Like the title states I have been looking to create a program that will loop over a text/input file (of numbers), then go on to find the Average for both odd and even numbers present in that file.
I have currently managed to create what is shown below which has resulted in being able to find the Average for the Odd Numbers. However I can't seem to get my head around being able to get the Average for the Even Numbers though.
I tried closing the scanner, opening up another scanner and making another while, if else loop like below and pretty much tried the opposite, other attempts to try and obtain the Even Average have ended up with the output being NaN, 0 or stuck on 26 at times (the 26 is probably down to my input file used but the math/s didn't make sense for obtaining the even average when I worked it out by hand)
This has been bothering me for some time now and was wonder if anyone could point me in the right direction on how I could obtain the Even Average as well as what I currently have.
Scanner scan = new Scanner(AvgOddEven.class.getResourceAsStream("Numbers.txt"));
int count = 0, sum = 0, evenCount = 0, oddCount = 0;
while (scan.hasNextInt()) {
int number = scan.nextInt();
if (number % 2 == 0) // even numbers are detected here
evenCount++; //those detected are counted here.
else
oddCount++;
sum += number;
count++; //Counts all numbers in the text file
}
System.out.println("Sum divided by odd = average: " + sum / oddCount); //This gets me the average of odd numbers
Below is the text file I used. (Apologies for it being quite long)
1
5
17
16
10
7
11
39
1
15
13
I don't think your code does what you think it does. No matter whether you number is odd or even, you are always adding to the
sum
. So in fact your current code is currently dividingsum/oddCount
which the sum of all numbers divided by the number (count) of odd numbers.To fix this and implement the average of even numbers, you should keep two separate variables for the
evenSum
andoddSum
.Your javascript modified would like something like this:
One final thing to be aware of is the difference between integer division and floating point division. Since you've declared all your variable as
int
s, your average will perform integer division, which truncates any decimal portion. To perform floating point division, at least one of your operands must be a floating point type. I've handled that by changing the type of thesum
variables to a floating point type (aDouble
or double-precision float).