簡體   English   中英

在給定的JUNIT測試第2部分中,找到與平均值最接近的數組中的值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM