Exercise
Array of positive and negative numbers
Objetive
Write a java program to ask the user for 10 real numbers and display the average of the positive ones and the average of the negative ones.
Example Code
import java.util.*;
public class Main
{
public static void main(String[] args)
{
float[] numbers = new float[10];
float totalPositive = 0.0f;
float totalNegative = 0.0f;
int countPositive = 0;
int countNegative = 0;
for (int i = 0;i < 10;i++)
{
System.out.printf("Number %1$s= ",i + 1);
numbers[i] = Float.parseFloat(new Scanner(System.in).nextLine());
}
for (int i = 0;i < 10;i++)
{
//Negative
if (numbers[i] < 0)
{
totalNegative = totalNegative + numbers[i];
countNegative++;
//Positive
if (numbers[i] > 0)
{
totalPositive = totalPositive + numbers[i];
countPositive++;
}
System.out.printf("Average numbers negatives = %1$s" + "\r\n",totalNegative / countNegative);
System.out.printf("Average numbers positives = %1$s" + "\r\n",totalPositive / countPositive);
}
}