Java – how to find minimum and maximum values by integer sequence?
•
Java
I'm new to coding. I try to use math Min and math The max method finds the minimum and maximum values of an integer sequence I think I've found most things, but when I test it, the minimum value is - 2147483648 and the maximum value is 2147483647 How can I change it?
/** * 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; } }
This is 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"); } }
Solution
Exchange minimum and maximum initial conditions 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 less than min_ Value (or greater than max_value)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码