簡體   English   中英

Java-如何按整數序列查找最小值和最大值?

[英]Java- How to find min and max values in sequence of integers?

我對編碼很新,我試圖通過使用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");
    }
}

交換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 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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