简体   繁体   中英

Is it possible to pass input.next - after verification - directly to a method as parameters in a variable length argument list? <in java>

package compute.greatest.common.denominator;

import java.util.Scanner;

public class computeGreatestCommonDenominator{
    private static Scanner input;

    public static void main(String[] args) {
        input = new Scanner(System.in);

        final int MAX = 20;
        final int MIN = 2;

        System.out.println("Enter between " + MIN + " and " + MAX + " numbers ( inclusive ) to find the GCD of: ");

        for(int i = 0; input.nextInt() != '\n'; i++) {      // Normally I would use a for loop to populate input into 
            if(input.nextInt() < MIN) {                     // an array and pass the array to method gcd().
                System.out.println("ERROR! That number is not within the given constraints! Exiting.......");
                System.exit(1);     // Any non-zero value, is considered an abnormal exit.
            }                                               

    }

    public static int gcd(int... numbers) {
        int greatestCommonDenominator = 0;
    }
}

Normally I would use a for loop to populate input into an array and pass that to method gcd(int... numbers). However, that seems to be a case of redundancy to me - passing an array to a variable length argument list, which is treated as an array. First let me say that I'm still in the learning phase of java and, while understanding variable length argument lists, it's not a confident understanding. Is there a way to verify the input data and pass it, one by one, in the loop, directly to the variable length argument list - without using an array? With an array seems redundant to me and without seems illogical :/

I think you are misunderstanding the use of variable length parameters (varargs) here.

Varargs are nice syntactic sugar because it makes this code:

int[] ints = {1, 2, 3};
gcd(ints);

more elegant:

gcd(1, 2, 3);

That is the purpose of varargs.

If you don't have or expect code like this:

int[] ints = {1, 2, 3};
gcd(ints);

then varargs is not so useful, and certainly don't force your code fit into this varargs thing.

My suggestion is that you keep your code the way it is, or you can change the varargs into a normal array parameter if you don't need to use the varargs feature anywhere else in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM