简体   繁体   English

在给定的JUNIT测试第2部分中,找到与平均值最接近的数组中的值

[英]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. 我的findMiddle()方法中的第一个for循环应该在数组列表中找到数组的AVERAGE,但是我的第二个for循环应该在数组中找到最接近该平均值的值。 However, Java is not even accepting my version of it. 但是,Java甚至不接受我的版本。 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. 我能够找到平均值,现在Java不接受我找到的最接近平均值的值。

The reason it doesn't consider the second for loop is the return statement. 它不考虑第二个for循环的原因是return语句。 Since return statement is going to be executed all the time it will never consider the second for loop. 由于return语句将一直执行,因此永远不会考虑第二个for循环。 Thus the control flow is changing and never coming back to that method. 因此,控制流程在变化,永远不会回到该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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