简体   繁体   中英

Arguments of variable number of integers in method in java

Question: Write a method that takes as input a variable number of integers. The method should return the average of the integers as a double. Write a full program to test the method.

That code below creates an array of 10 integers and finds their average. However, I need it to create a variable number of arguments (int...a) where any number of integers entered can be averaged. Can someone help me.Thanks.

My code:

package average.pkgint;
import java.util.Scanner;
public class AverageInt {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int [] number = new int [10];
        Scanner b = new Scanner(System.in);
        System.out.println("Enter your 10 numbers:");
        for (int i = 0; i < number.length; i++) {
             number[i] =  b.nextInt() ;

        }

        System.out.println("The average is:"+Avnt(number));

    }

    public static int  Avnt(int [] a){//declare arrays of ints
        int result = 1;      
        int sum = 0;
        //iterate through array
        for (int num : a) {
              sum += num; 
        }
            double average = ( sum / a.length);//calculate average of elements in array
            result = (int)average;

             return result;

    }

    }

This is a way of getting as many variables as you want to a method and going through them all:

public static void testVarArgs(int... numbers){
    for(double u: numbers) {
        System.out.println(u);
    }
}

Just change your method declaration to a variable length parameter:

public static int  Avnt(int ... a){//declare variable int arguments

When you use a variable length parameter, you supply the values in the method invocation. For example,

    System.out.println(Avnt(1,2,3));
    System.out.println(Avnt(1,2,3,4,5,6,9,9,9,10,10));

Actually, this looks like it meets your requirements. Just add method calls in your main() similar to these.

If you don't want to read the number of integers as the first input you can declare a stack in stead of an array

Stack<Integer> numbers=new Stack<>()

and then you can add the numbers with the add method.

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