0

我应该从数字序列中得到最小和最大的数字。我知道每种方法的方法体可能都不正确。有什么帮助吗?

public class DataSet
{
  private int sum;
  private int count;
  private int largest;
  private int smallest;

  public DataSet()
   {
   sum = 0;
   count = 0;
   largest = 0;
   smallest = 0;
   }

 public void addValue(int x)
  {
   sum = sum + x;
   count++;
  }

 public int getSum()
 {
   return sum;
 }

 public double getAverage()
 {
   double average = sum/count;
   return average;
 }

 public int getLargest()
 {
   int largest = Integer.MAX_VALUE;//not giving right answer, don't know how to use
   return largest;
 }

  public int getSmallest()
 {
   int smallest = Integer.MIN_VALUE;//not giving right answer, don't know how to use
   return smallest;
  }
}

如果需要,这是测试器类,尽管我认为问题不在于这里。

 public class DataSetTester
 {  
   public static void main(String[] args)
    {
    DataSet myData = new DataSet();
    myData.addValue(100);
    myData.addValue(5);
    myData.addValue(4);
    myData.addValue(2);

    System.out.println("Sum = " + myData.getSum());
    System.out.println("Average = " + myData.getAverage());
    System.out.println("Largest value = " + myData.getLargest());
    System.out.println("Smallest value = " + myData.getSmallest());
   }
   }
4

3 回答 3

5

Integer.MAX_VALUE并返回可由值Integer.MIN_VALUE表示的最大和最小数字Integer

相反,在您添加方法中,您需要在添加值时比较它们,您可以使用Math.minandMath.max使比较更容易,例如...

private int smallest = Integer.MAX_VALUE;
private int largest = Integer.MIN_VALUE;

public void addValue(int x)
{
    smallest = Math.min(smallest, x);
    largest = Math.max(largest, x);
    sum = sum + x;
    count++;
}
于 2013-10-07T03:30:57.887 回答
0

这是一项相当简单的任务,您可能只是想得太难了。添加值时,必须通过向 addValue() 添加一些 if 语句来检查是最小值还是最大值。

    public void addValue(int x)
    {
        sum = sum + x;
        count++;
        if(x > largest)
             largest = x;
        else if(x < smallest)
             smallest = x;
    }

之后,您只需在 getSmallest 和 getLargest 方法中返回最大和最小的。它们应该如下所示:

    public int getLargest()
   {
   return largest;
   }

   public int getSmallest()
   {
   return smallest;
   }
于 2013-10-07T03:35:16.640 回答
0

有几种方法可以做到这一点。一种简单的解决方案是修改您的addValue()方法:

private int smallest = Integer.MAX_VALUE;
private int largest = Integer.MIN_VALUE;

public void addValue(int x) {
   sum = sum + x;
   count++;
   this.largest = (x > this.largest) ? x : this.largest;
   this.smallest = (x < this.smallest) ? x : this.smallest;
}

此外,您将需要删除这些行:

int largest = Integer.MAX_VALUE;

int smallest = Integer.MIN_VALUE;

从吸气剂。

于 2013-10-07T03:35:35.480 回答