Reputation: 55
For class I am writing a program that accepts a stream of positive integers. The program will stop accounting for numbers and compute the average once a negative number is entered into the console.
My issue is, I keep writing while loops that account for the negative entered. How do I stop this? I have tried the following
do{
if (number < 0){
break;
} else if ( number >= 0) {
number = input.nextDouble();
DivideBy++;
sum+=number;
}
}while (number >= 0);
When entering 1.1, 1.9, 3, and -1, the program prints 1.25, when the correct answer is 2.
Here is another example of what I have tried:
do {
number = input.nextDouble();
DivideBy++;
sum+=number;
}while (number >= 0);
Any help is appreciated.
Upvotes: 1
Views: 6181
Reputation: 11
Try this:
Scanner input = new Scanner(System.in);
double number = 0;
double sum = 0;
int divideBy = 0;
double avg = 0;
while(number >= 0) {
System.out.println("Enter number: ");
number = input.nextDouble();
if(number < 0){
break;
}
sum+=number;
divideBy++;
avg = sum/divideBy;
}
System.out.println(avg);
Your if statement should come after the number has been read from the keyboard :]
Upvotes: 1
Reputation: 603
Read the number before the if condition. Try this.
do {
number = input.nextDouble();
if (number < 0) {
break;
} else if (number >= 0) {
DivideBy++;
sum += number;
}
} while (number >= 0);
Upvotes: 0
Reputation: 271135
What you are doing now is checking whether the number is negative after you incremented DivideBy
and added the number to the sum.
You can easily fix this by undoing what you did after a negative number.
// outside the loop:
sum -= number;
DivideBy--;
Then you will get the correct result.
Or, you can do it like this - check negative first, then add it to sum.
Scanner s = new Scanner(System.in);
int num = s.nextInt();
int count = 0;
int sum = 0;
while (num > 0) {
sum += num;
count++;
num = s.nextInt();
}
System.out.println(sum / count);
Upvotes: 0
Reputation: 11
Try this out, it worked for me:
while(number >= 0){
total = number + total;
} //Your average logic here//
Upvotes: 0