簡體   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