Reputation: 1
I am trying to put multiple numbers into a min and max method. I know that in a min and max method only two methods are allowed. However, I have more than two numbers and I don't have a clue what I'm doing.
This code is also on reply.it:
int age5 = 75;
int age6 = 62;
int age7 = 89;
int age8 = 90;
int age9 = 101;
int youngestAge = Math.min()
int oldestAge = Math.max()
Upvotes: 0
Views: 85
Reputation: 990
With JDK 8+ you can use streams
public static void main(String [] args) {
int min = IntStream.of(75, 62, 89, 90, 101).min().getAsInt();
int max = IntStream.of(75, 62, 89, 90, 101).max().getAsInt();
}
And another example with summary statistics
public static void main(String [] args) {
final IntSummaryStatistics s = IntStream.of(75, 62, 89, 90, 101).summaryStatistics();
System.out.println(s.getMin());
System.out.println(s.getMax());
}
Upvotes: 0
Reputation: 1066
Varargs is a feature that allow methods to receive N params. So you can write a method with it that can receive a indefinite number of ages and returns the smaller one:
public int smallerNumber(int... numbers) {
int smallerNumber = 0;
int previousVerified = numbers[0];
for(int i = 1; i < numbers.length; i++) {
smallerNumber = Math.min(numbers[i], numbers[i-1]);
if(previousVerified <= smallerNumber)
smallerNumber = previousVerified;
else
previousVerified = smallerNumber;
}
return smallerNumber;
}
Calling this:
smallerNumber(65, 654, 7, 3, 77, 2, 34, 6, 8);
Returns this: 2
.
Upvotes: 0
Reputation: 63
You could use a loop
int[] age = {75, 62, 89, 90, 101};
int youngestAge = age[0];
int oldestAge = age[0];
for(int i = 1; i < age.length; i++) {
youngestAge = Math.min(youngestAge, age[i]);
oldestAge = Math.max(oldestAge, age[i]);
}
System.out.println(youngestAge+ " " + oldestAge);
Upvotes: 2