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


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

这是varargs的目的。

如果您没有这样的代码:

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

那么varargs并不是那么有用,当然也不强制您的代码适合此varargs。

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

相关内容

最新更新