Reputation: 35
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
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:
Upvotes: 2
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