Joey Cage Joey Cage - 2 months ago 9
Java Question

An array that will declare 5 random numbers from 0 to 100. Then it will average all the numbers that are over 70

Well hello everyone. Recently arrays were taught in my class, and this is the homework question that I need to answer.

Write a complete program that declares an array of any five integers, from 0 to 100 , and averages only those integers which are greater than 70 .

Here is my code I have written so far.

import java.util.Random;
public class TestLoop{

public static void main(String[] args){
Random Rnum = new Random();
int[] ar1 = new int[100];
for(int i = 0; i < 5; i++) {
ar1[i] = Rnum.nextInt(100);
System.out.print(ar1[i] + " ");

if(ar1[i] > 70)

System.out.print(ar1[i] + " ");
}
}
}


This allows me to get my five random numbers, but I can't seem to figure out how to average the ones that will be over 70. The last few lines of code are my attempt to isolate the numebrs that are over 70 from the others are not.

Answer

try this:

public static void main(String[] args){
    Random Rnum = new Random();
    int[] ar1 = new int[100];
    int counter=0;
    double total=0;
    for(int i = 0; i < 5; i++) {
        ar1[i] = Rnum.nextInt(100);
           System.out.print(ar1[i] + "  ");

        if(ar1[i] > 70)
        {    
            total+=ar1[i];
            counter++;
            System.out.print(ar1[i] + "  ");
        }
    }
    if(counter>0)
    {
        double average=total/counter;
        System.out.println("average="+average);
    }

}