llooll
llooll

Reputation: 35

Elements of array differ from average and less than number

I have small problem maybe anyone can help me. I have a random elements array, then count the average and scan a number from the user. I'm looking numbers of elements array differ than average less than the number scanned from user.

public static double average(int[][] array){
    double average = 0;
    int sum = 0;
    for(int i = 0; i < array.length; i++){
        for(int j = 0; j < array.length; j++){
          sum += array[i][j];
        }
    }
    average = (double) sum/array.length;
    return average;
}

public static void main(String[] args) {
    Random rnd = new Random();
    Scanner scan = new Scanner(System.in);

    int[][] array = new int[4][4];
    for(int i = 0; i < array.length; i++){
        for(int j = 0; j < array.length; j++){
            array[i][j] = rnd.nextInt(10);
        }
    }

    int a = scan.nextInt();
    average(array);
    int elements = 0;
    for(int i = 0; i < array.length; i++){
    for(int j = 0; j < array.length; j++){
        if(array[i][j]) {
          // ?? need help here
        }
    }
}

Upvotes: 3

Views: 66

Answers (2)

GhostCat
GhostCat

Reputation: 140641

Here:

average(array);

You are calling your average method ... but you are not using its result!

double averageForArray = average(array);

allows you to later compare against that value, like:

int deltaGivenByUser = scan.nextInt();

for(int i = 0; i < array.length; i++){
  for(int j = 0; j < array.length; j++){
    if(Math.abs(array[i][j] - average) >= deltaGivenByUser) {
      ...

Notes:

  • The above is on a "pseudo code" level; I didn't ran it through the compiler; so beware of subtle bugs/typos. My code is meant to give you an idea how to do things; it is not meant for "copy/paste/solved".
  • Please look into your naming. A variable name like "a" doesn't say anything. My name deltaGivenByUser is probably not perfect, but at least it gives some idea what that variable will be used for.
  • Then have a closer look how to work with scanners; for example by using the hasNextInt() method. Right now your code will fail when the user provided something that is not a number
  • Also separate things: you have a nice method for computing that average; you could also create another method that receives that value provided by the user; to do that processing outside of the main method

Upvotes: 2

Adriaan Koster
Adriaan Koster

Reputation: 16205

This is risky:

for(int i = 0; i < array.length; i++){
  for(int j = 0; j < array.length; j++){
  sum += array[i][j];
}

You are using the size of the outer array for both loops. Better to use the actual size of the sub array:

 for(int i = 0; i < array.length; i++) {
      int[] subArray = array[i];
      for(int j = 0; j < subArray.length; j++){
      sum += subArray[j];
 }

Upvotes: 1

Related Questions