繁体   English   中英

是否可以在验证后将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);

这就是varargs的目的。

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

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

那么varargs并不是那么有用,当然不要强迫您的代码适合varargs。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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