Here is a problem given to me. The challenge for me is knowing how to find the AVERAGE from an array list and the value in the array that is closest to that average. All by writing code that can execute this with any array given in the test.
Here's the test I was given to write a class for:
import static org.junit.Assert.*;
import org.junit.Test;
public class Question2Test
{
int[] arrayInts = {1, 1, 3, 4, 9};
private Question2 avg1;
private Question2 avg2;
private Question2 avg3;
@Test
public void testFindMiddle()
{
Question2 avg1 = new Question2();
assertEquals(1, avg1.getAverage());
Question2 avg2 = new Question2();
assertEquals(4, avg2.getAverage());
Question2 avg3 = new Question2();
assertEquals(0, avg3.getAverage());
}
//find what I need to do with "getAverage"
}
what I have so far:
/**
* Find the value in an array that is closest to the average.
*/
public class Question2
{
private int avg;
public double findMiddle(int[] arrays)
{
//Find the average
double sum = 0;
for(int i = 0; i < arrays.length; i++)
{
sum += arrays[i];
}
double avg = sum/arrays.length;
return avg;
// Now Find the value in an array that is closest to the average:
for(int i = 0; i < arrays.length; i++)
{
int arrays[i] = Math.abs(arrays[i] + 1);
if(arrays[i] == avg)
{
return arrays[i];
}
}
}
public int getAverage(int[] array) // is a getter: a method whose purpose is to return the value stored in an instance variable!
{
return avg;
}
}
So the first problem is it does not take my seconds for loop at all. I was able to find the average, now Java is not accepting my finding the value closest to it.