Home > Mobile >  How to target the elements of the Varargs method in Java inside the function?
How to target the elements of the Varargs method in Java inside the function?

Time:05-16

I wanted to use the varags method to take the input of various integers and find out the maximum & minimum among them.

public class MINMAX {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        int c = in.nextInt();
        Maximum(a,b,c);
        Minimum(a,b,c);
    }
    static void Maximum(int ...v) {
        int max = Math.max(a,Math.max(b,c));
        System.out.println("The Largest no. is: " max);
    }
    static void Minimum(int ...v) {
        int min = Math.min(a,Math.min(b,c));
        System.out.println("The Smallest no. is: " min);
    }
}

Here, I'm taking input of a,b,c from the user to find out the max & min. but want to know how can i target the specific elements in Varargs Method.

CodePudding user response:

To begin, imagine how many Math.min you need if you have 10 inputs instead of 3.

What you need is a method which can accept different number of inputs(that's why we have varargs), so that there is no need to change anything when you want to support more inputs. Hence you need to handle varargs(which can be treated as an array) instead of specific element.

In addition, by using IntStream#summaryStatistics, you can get min and max in one shot.

    static void maximumAndMaximum(int... v) {
        IntSummaryStatistics statistics = IntStream.of(v).summaryStatistics();
        System.out.println("The Smallest no. is: "   statistics.getMin());
        System.out.println("The Largest no. is: "   statistics.getMax());
    }

CodePudding user response:

You can access it as an int primitive type array that you have given in the method parameter. e.g.

 static void Maximum(int ...v) {
      int max = Math.max(v[0],Math.max(v[1],v[2]));
      System.out.println("The Largest no. is: " max);
 }

 static void Minimum(int ...v) {
     int min = Math.min(v[0],Math.min(v[1],v[2]));
     System.out.println("The Smallest no. is: " min);
 }

I recommend that you make it a habit to check the size of the directory and other controls before starting the process.

CodePudding user response:

The varargs syntax (... parameterName) is just another way of saying that the parameter is an array isn't it? The java.util.Collections class has methods on it that you might find useful. I suspect you may need to convert the array into something that implements the Collection interface to use them (e.g. java.util.ArrayList).

  • Related