在给定的JUNIT测试中,找到最接近平均值〜的数组中的值

时间:2018-08-06 21:26:37

标签: java arrays junit average

这是我遇到的一个问题。对我来说,挑战在于如何从数组列表中找到平均值,以及数组中与该平均值最接近的值。所有这些都通过编写可以对测试中给出的任何数组执行此代码的代码来完成。

这是我为编写类的测试:

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"
}

我到目前为止有什么:

/**
 * 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;
}   

}

所以第一个问题是循环根本不需要我花费几秒钟的时间。我能够找到平均值,现在Java不接受我找到的最接近平均值的值。

1 个答案:

答案 0 :(得分:1)

正如您所说,问题有两个不同的部分:

  1. 找到平均值
  2. 在数组中找到最接近该平均值的数字。

关于问题1,在您的代码中您有正确的想法,但有错误的实现。您想要将数组中的所有元素加起来,然后将总和除以数组中的元素数量。实际上,您需要做的就是将除法从循环中取出。看起来像这样:

double sum = 0;
for(int i = 0; i < arrays.length; i++)
        {
            sum += arrays[i]; //the += takes the current value of sum and adds the array[i] value to it. 
        }    
double avg = sum/arrays.length; //Since sum is a double avg can be a double as well.

对于第二部分,您想在数组中找到最接近该平均值的数字。使用Math.abs()方法,您可以获取两个数字之间的差的绝对值。使用此方法,您可以循环访问数组中的所有元素,对它们调用Math.abs()方法,然后保存结果最小的元素。

相关问题