Issue
(Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number. Here is a sample run:
Enter an integer, the input ends if it is 0: 1 2 -1 3 0
The number of positives is 3
The number of negatives is 1
The total is 5.0
The average is 1.25
I have 2 major issues. 1) I cannot get the loop to stop. 2) even if I did, the average comes up short. Using the example above, my average is always 1.0, not 1.25 as it should be. It's like the program is reading 5 numbers total instead of the 4 numbers that equate to 5. What is seen in the code below is all I can use: Bare basics of java...
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int positive = 0, negative = 0, total = 0, count = 0;
float average;
System.out.println("Enter the number: ");
int number = input.nextInt();
while(number != 0) {
total += number;
count++;
if(number > 0){
positive++;
}
else if(number < 0){
negative++;
}
average = total / count;
System.out.println("The number of positives is "+ positive);
System.out.println("The number of negatives is "+ negative);
System.out.println("The total is "+ total);
System.out.println("The average is "+ average);
}
}
}
Solution
You need to read more numbers. You read one value before your loop. You could do something like
int number;
while((number = input.nextInt()) != 0) {
total += number;
count++;
if(number > 0){
positive++;
} else if(number < 0) {
negative++;
}
} // <-- end loop body.
float average = total / (float) count; // <-- not integer math.
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total is " + total);
System.out.println("The average is " + average);
Answered By - Elliott Frisch