[英]Find the value in an array that is closest to the average with given JUNIT test Part 2
我的findMiddle()方法中的第一个for循环应该在数组列表中找到数组的AVERAGE,但是我的第二个for循环应该在数组中找到最接近该平均值的值。 但是,Java甚至不接受我的版本。 它不接受什么?
这是我为编写类的测试:
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?
}
我到目前为止所拥有的:
/**
* 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不接受我找到的最接近平均值的值。
它不考虑第二个for循环的原因是return语句。 由于return语句将一直执行,因此永远不会考虑第二个for循环。 因此,控制流程在变化,永远不会回到该方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.