나는 코딩이 새로 생겼다. Math.min과 Math.max 메서드를 사용하여 정수의 시퀀스의 최소값과 최대 값을 찾으려고한다. 나는 대부분의 것을 알아 냈다고 생각하지만, 테스트 할 때 최소값은 -2147483648이고 최대 값은 2147483647입니다. 어떻게 변경할 수 있습니까? 여기Java - 정수 순서에서 최소값과 최대 값을 찾는 방법은 무엇입니까?
/**
* 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");
}
}
후손을 위해 컬렉션에서 최대 및 최소 요소를 원한다면 실재로 TreeSet과 같은 SortedSet을 사용하는 것이 좋습니다. –
문제는 Math.max와 Math.min을 요구했지만, 미래를 염두에 두겠습니다. 고마워요. – Tricia
use int highest = Math.MIN_VALUE; int lowest = Math.MAX_VALUE; – Renukaradhya