0

I don't fully understand varargs, and I found this little exercise that only got me confused. Can someone comment it step-by-step and tell me why are varargs useful? Thanks in advance.

/*********************************************************************************
 * (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;
    }
}
user412308
  • 59
  • 9
  • 2
    `int... numbers` is equivalent to `int[] numbers` as far as the method body is concerned. When calling the method, it allows you to write `getRandom(1,2,3)` instead of `getRandom(new int[]{1,2,3})`. – Eran Nov 11 '16 at 09:16
  • `numbers` will behave like an array which potentially has multiple entries in it. Have you tried debugging your code to see for yourself? – Tim Biegeleisen Nov 11 '16 at 09:17
  • Hint: if you don't understand some concept, try using some search engine and to read some documentation. Why do you expect that the text **written** down by us for you ... would be any different than the many texts written down about this subject ... that are already available to you? – GhostCat Nov 11 '16 at 09:26

0 Answers0