简体   繁体   中英

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

I'm fairly new to coding and I'm trying to find the minimum and maximum of a sequence of integers by using Math.min and Math.max methods. I think I have most things figured out, but when I test it the minimum is -2147483648 and the maximum is 2147483647. How can I change that? Here's the code:

/**
 * 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;
    }
}

Here's the tester:

/**
 * 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");
    }
}

Swap the initial conditions for smallest and largest . Change

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

to

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

Because no int value is smaller than MIN_VALUE (or larger than MAX_VALUE ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM