Java - 有人能解释一下这段代码中的varargs是做什么的吗?

时间:2016-11-11 09:15:23

标签: java variadic-functions

我不完全理解varargs,我发现这个让我困惑的小练习。有人可以一步一步地评论它并告诉我为什么varargs有用吗?提前谢谢。

/*********************************************************************************
 * (Random number chooser) Write a method that returns a random number between    *
 * 1 and 54, excluding the numbers passed in the argument. The method header is   *
 * specified as follows:                                                          *
 * public static int getRandom(int... numbers)                                    *
 *********************************************************************************/

public class Test {

    /** Method getRandom returns a random number between 1 and 54,
     *   excluding the numbers passed in the argument.*/
    public static int getRandom(int... numbers) {
        int num;    // Random number
        boolean isExcluded; // Is the number excluded
        do {
            isExcluded = false;
            num = 1 + (int)(Math.random() * 5);
            for (int e: numbers) {
                if (num == e)
                    isExcluded = true;
            }
        } while (isExcluded); // Test if number is Excluded
        return num;
    }
}

0 个答案:

没有答案