我是一个编程新手,正在尝试使用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");
}
}
SortedSet
(如TreeSet
)是一个不错的选择。 - Tim Biegeleisen