I'm fairly new to Java, and have been working on arrays. The task was :
My code so far: (keep in mind, it's pretty rough, I got kinda lost towards the end.) All I'm asking is for someone to explain/help with how to find the 50+- average, and searching for user input in the array
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] nums = new int[100];
for (int i = 0; i < nums.length; i++){
nums[i] =(int) (Math.random()*1000);
}
for (int i = 0; i < nums.length; i++){
if (i % 20 == 0){
System.out.println("\n");
}
System.out.print(nums[i] + " ");
}
int sum = 0;
for(int i = 0; i< nums.length; i++){
sum += nums[i];
}
int average;
average = sum/(nums.length);
System.out.println("\n\nThe average equals: "+ average);
int fifty = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] <= average - 50 && nums[i] >= average + 50){
fifty++;
}
}
System.out.print("Number of values within 50 of the average: " + fifty);
int usrVal;
System.out.println("\nEnter a value to test: ");
usrVal = in.nextInt();
}
}
so as you know what your average is
then loop through your array and compare each number to the average
if (Math.abs (nums[i] - average) < 50) {
System.out.println (nums[i]);
// or count it or whatever
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments