简体   繁体   中英

Find the value in an array that is closest to the average with given JUNIT test Part 2

The first for loop in my findMiddle() method should find the array's AVERAGE in the array list, but my second for loop should find the value in the array that is closest to that average. However, Java is not even accepting my version of it. What does it not accept?

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(arrayInts));
         Question2 avg2 = new Question2();
         assertEquals(4, avg2.getAverage(arrayInts));
         Question2 avg3 = new Question2();
         assertEquals(0, avg3.getAverage(arrayInts));
    }
//find what I need to do with "getAverage" == return avg?
}

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.

The reason it doesn't consider the second for loop is the return statement. Since return statement is going to be executed all the time it will never consider the second for loop. Thus the control flow is changing and never coming back to that method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM