【问题标题】:Java- How to find min and max values in sequence of integers?Java-如何在整数序列中找到最小值和最大值?
【发布时间】:2017-01-10 00:49:10
【问题描述】:

我对编码还很陌生,我正在尝试使用 Math.min 和 Math.max 方法找到整数序列的最小值和最大值。我想我已经弄清楚了大部分事情,但是当我测试它时,最小值是 -2147483648,最大值是 2147483647。我该如何改变它? 代码如下:

/**
 * A class to find largest and smallest values of a sequence.
 **/
public class DataSet
{
  private int smallest = Integer.MIN_VALUE;
  private int largest = Integer.MAX_VALUE;
  /**
   * Adds in integer to sequence.
   * @param x the integer added
   */
  public void addValue(int x)
   {
    smallest = Math.min(smallest, x);
    largest = Math.max(largest, x);
   }
  /**
   * Returns the smallest value.
   * @return the smallest value
   */
  public int getSmallest() 
   {
    return smallest;
   }
  /**
   * Returns the largest value.
   * @return the largest value
   */
  public int getLargest()
    {
      return largest;
    }
}

这是测试仪:

/**
 * A class to test the DataSet class.
 */
public class DataSetTester
{
    public static void main(String[] args)
    {
        DataSet myData = new DataSet();
        myData.addValue(11);
        myData.addValue(4);
        myData.addValue(6);
        myData.addValue(9);
        System.out.println("Smallest: " + myData.getSmallest());
        System.out.println("Expected: 4");
        System.out.println("Largest: " + myData.getLargest());
        System.out.println("Expected: 11");
    }
}

【问题讨论】:

  • 为了子孙后代,在现实生活中,如果您想要集合中的最大和最小元素,那么使用 SortedSetTreeSet 是一个不错的方法。
  • 问题要求 Math.max 和 Math.min,但我会记住这一点以备不时之需,谢谢。
  • 使用int最高=Math.MIN_VALUE; int 最低=Math.MAX_VALUE;

标签: java max min


【解决方案1】:

交换smallestlargest 的初始条件。改变

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

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

因为没有int 的值小于MIN_VALUE(或大于MAX_VALUE)。

【讨论】:

  • @Tricia 使用调试器应该可以帮助您找到这个错误。
猜你喜欢
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 2021-04-09
  • 2018-09-14
  • 1970-01-01
相关资源
最近更新 更多