是否可以将 input.next - 在验证后 - 作为可变长度参数列表中的参数直接传递给方法? <in java>

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

通常我会使用 for 循环将输入填充到数组中并将其传递给方法 gcd(int... numbers)。然而,这对我来说似乎是一个冗余的情况——将一个数组传递给一个可变长度的参数列表,它被视为一个数组。 首先我要说的是,我还处于 java 的学习阶段,在理解可变长度参数列表的同时,还不是一个自信的理解。 有没有办法验证输入数据并在循环中一个一个地传递它, 直接到可变长度参数列表 - 不使用数组? 有数组对我来说似乎是多余的,没有数组似乎不合逻辑:/

我认为您误解了此处可变长度参数 (varargs) 的使用。

Varargs 是很好的语法糖,因为它使这段代码成为:

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

更优雅:

gcd(1, 2, 3);

这就是可变参数的目的。

如果您没有或不期望这样的代码:

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

那么 varargs 就没那么有用了,当然不要强迫你的代码适合这个 varargs 东西。

我的建议是保持代码不变,或者如果不需要在代码中的其他任何地方使用可变参数功能,则可以将可变参数更改为普通数组参数。