Numbers below average

1

I need to average 20 numbers and have all numbers smaller than average.

package pag1;

import java.util.Arrays;
import java.util.Scanner;

public class ex2 {
public static void main (String[] args){
    Scanner x = new Scanner(System.in);

    int soma = 0;
    int posicao = 0;
    double [] numeros = new double [20];
    System.out.println("Digite 20 números para obter a média dos mesmos:");

    while (posicao < numeros.length){
        numeros [posicao] = x.nextDouble();
        posicao++;          
    }
    System.out.println(Arrays.toString(numeros));
    for(int i=0; i<numeros.length; i++){
        soma += numeros[i];

    }
    int media = soma / numeros.length;
    System.out.println("soma: " + soma);
    System.out.println(media);

}

}

There was only part of showing the numbers smaller than the average, but I have no idea how.

    
asked by anonymous 04.07.2017 / 00:18

3 answers

1

First, I think your media variable has to be double. Solution: Just go through the vector and check which numbers are smaller than the average!

excerpt:

for(int i=0; i<numeros.length; i++){
    if(numeros[i] < media)
        System.out.println(numeros[i]);

}
    
04.07.2017 / 00:33
1

Complementing existing responses, I introduce one using streams and lambdas , which will make printing the below-average values in a more compact way.

Calculation of the mean:

double media = Arrays.stream(numeros).average().getAsDouble();

Printing below-average values:

Arrays.stream(numeros).filter(num->num < media).forEach(num->System.out.println(num));

When filter has only kept the elements below the average with num->num < media , and with forEach it shows the remaining ones.

See the code working on Ideone

    
04.07.2017 / 12:19
0

I found a solution:

package pag1;

import java.util.Arrays;
import java.util.Scanner;

public class ex2 {
public static void main (String[] args){
    Scanner x = new Scanner(System.in);

    double [] menoresque = new double [20];
    int soma = 0;
    int posicao = 0;
    double [] numeros = new double [20];
    System.out.println("Digite 20 números para obter a média dos mesmos:");

    while (posicao < numeros.length){
        numeros [posicao] = x.nextDouble();
        posicao++;          
    }
    System.out.println(Arrays.toString(numeros));
    for(int i=0; i<numeros.length; i++){
        soma += numeros[i];

    }
    int media = soma / numeros.length;
    System.out.println("soma: " + soma);
    System.out.println(media);
for(int i=0; i<numeros.length; i++){
    if (numeros[i] < media) {
    menoresque[i]=numeros[i];
    }

}for(int i=0; i<menoresque.length; i++){
    if(menoresque[i] != 0){
System.out.print(menoresque[i]+", ");
    }
}
}
}
    
04.07.2017 / 00:50