For full functionality of this site it is necessary to enable JavaScript. Here are the instructions how to enable JavaScript in your web browser.

All for Joomla All for Webmasters
Close

Java: Count positive and negative numbers and compute the average of numbers

package chapter5_5_1;
import java.util.Scanner; 
/**
 *
 * @author Siavash Bakhshi
 */
public class Chapter5_5_1
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        // Create a Scanner
        Scanner input = new Scanner(System.in);
        int number = -1;
        int positive = 0;
        int negative = 0;
        int count = 0;
        int total = 0;
        double avg;  
        System.out.print("Enter an integer, the input ends if it is 0: ");
        while(number != 0)
        {
            number = input.nextInt();
            total += number;
            count++;
            if (number < 0 || number > 0)
            {
                if (number > 0)
                {
                    positive++;
                }
                else
                {
                    negative++;
                }
                
            }          
        }
        avg = ((double)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 " + avg);
    }
}
Java: Count positive and negative numbers and compute the average of numbers (805 downloads )