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


i'm new coding , i'm trying find minimum , maximum of sequence of integers using math.min , math.max methods. think have things figured out, when test minimum -2147483648 , maximum 2147483647. how can change that? here's code:

/**  * class find largest , smallest values of sequence.  **/ public class dataset {   private int smallest = integer.min_value;   private int largest = integer.max_value;   /**    * adds in integer sequence.    * @param x integer added    */   public void addvalue(int x)    {     smallest = math.min(smallest, x);     largest = math.max(largest, x);    }   /**    * returns smallest value.    * @return smallest value    */   public int getsmallest()     {     return smallest;    }   /**    * returns largest value.    * @return largest value    */   public int getlargest()     {       return largest;     } } 

here's tester:

/**  * class test 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 initial conditions smallest , 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 smaller min_value (or larger max_value).


Comments