简体   繁体   中英

How to fix this VarArgs build error?

Here's the main method:

package main;

import varArgs.VarArgs;

public class Main {

    public static void main(String[] args) {
        int answer;

        answer = VarArgs.sum(new int[]{1,2,3});
        System.out.println("sum of ints = " + answer);

        answer = VarArgs.sum(new int[]{1,2,3}, new int[] {100, 200, 300});
        System.out.println("sum of ints = " + answer);

    }
}

Here's the var args method:

package varArgs;

    public class VarArgs {
        /***
         * Add an array of integers
         * @param numbers Some array of integers
         * @return The sum of all the elements in num
         */
        public static int sum(int... numbers) {
            int result = 0;
            for (int i : numbers) {
                result += i;
            }
            return result;
        }   
    }

Here's the error I get: 错误

A varargs parameter can only accept a single array. If you want to pass in a variable number of arrays, you need to do this:

public static int sum(int[]... arrays) {
    int sum = 0;
    for (int[] numbers : arrays) {
        for (int i : numbers) {
            sum += i;
        }
    }
    return sum;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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