0

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()
4
  • Math.min(Math.min(age5, age6), age7) or make your own. Commented Feb 12, 2019 at 0:47
  • thank you so much. I'm not quite sure why there is a math.min in the parantheses though? Commented Feb 12, 2019 at 0:49
  • 2
    It's a nested method call. It is calling min and finding the smallest number between two of the elements, and then the result of that is passed to the outer call to min and compared to age7 Commented Feb 12, 2019 at 1:16
  • docs.oracle.com/javase/8/docs/api/java/util/stream/… Commented Feb 12, 2019 at 2:03

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.