Something wrong with computing the average
I have to compute the average in this program, but the average cannot consists of zero which ends the program. For example if I enter 1, 2, 3, -1, then 0 to exit, the average will be the sum (5) over 4 and not 5 since the last number, the zero does not go in the sum. Any help?
Thanks.
Code :
public class Problddm1 {
public static void main (String []args){
Scanner scan = new Scanner(System.in);
// Object declaration
int number = 1;
int sum = 0;
float average = 0;
float count = 0;
int posnum =0;
int negnum =0;
// While loop
do{
count++;
System.out.print("Enter a number, program exits on 0: ");
number = scan.nextInt();
sum = sum + number;
average = sum / count;
if (number <0) {
negnum++;
}
else if (number >0) {
posnum++;
}
} while (number != 0);
// Results
System.out.println("The number of positives is: " +posnum);
System.out.println("The number of negatives is: " +negnum);
System.out.println("The total is: " + count);
System.out.println("The average is: " +average);
}
}
Re: Something wrong with computing the average
A do-while loop will do something, and then check to see whether it should be repeated.
A while loop will check if something should be done, and if so, do it and repeat the check.
You want to do the latter. You're doing the former.
Re: Something wrong with computing the average
Still doesn't work :(
I switch the do{ with while (number != 0){ and deleted the while in the do :(
Stupid zero.
Re: Something wrong with computing the average
Quote:
Originally Posted by
maximus20895
Still doesn't work :(.
"It doesn't work" is one of the least informative statements you can make. What exactly did you try (an SSCCE answers that question). What does it do? What did you expect it to do?
Re: Something wrong with computing the average
Haha, sorry.
It does the same thing as the first which is when it calculates the average it adds the zero with it. So the average goes way down. I just want it to calculate any - or + numbers and not include the zero. It always includes the zero since you have to enter 0 in order to close the program.
I changed the do-while loop to a while loop.
Re: Something wrong with computing the average
You aren't scanning the next number until after you've already entered the while loop, which is why it's not working. You have a check to see whether the number is positive or negative. Why don't you do something similar to check that it's not zero?