【问题标题】:Arguments of variable number of integers in method in javajava中方法中可变整数个数的参数
【发布时间】:2014-07-29 04:22:32
【问题描述】:

问题: 编写一个将可变数量的整数作为输入的方法。该方法应将整数的平均值作为双精度值返回。编写一个完整的程序来测试该方法。

下面的代码创建了一个包含 10 个整数的数组并找到它们的平均值。但是,我需要它来创建可变数量的参数(int...a),其中输入的任意数量的整数可以被平均。谁能帮帮我。谢谢。

我的代码:

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;

    }

    }

【问题讨论】:

  • 不要使用int 作为sum 的类型。您只需 2 个整数 (Integer.MAX_VALUE + 1 == Integer.MIN_VALUE) 就可以实现溢出。请改用 long 或 double。

标签: java methods integer arguments variadic-functions


【解决方案1】:

只需将您的方法声明更改为可变长度参数:

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

当您使用可变长度参数时,您在方法调用中提供值。例如,

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

实际上,这看起来符合您的要求。只需在 main() 中添加类似于这些的方法调用。

【讨论】:

  • 那我该如何重写这个程序。我还需要循环遍历main中的数组吗?此外,由于它现在是可变数量的参数,我仍然需要设置数组大小。
  • 保持你的方法不变。 “a”将成为您方法中的一个数组。您需要做的就是按上述方式更改声明。
  • 谢谢..但是我可以平均的整数数量仍然限制为 10,因为这是我的主要数组的大小。如何让它无限?
  • 参见上面的 System.out.println() 语句。
【解决方案2】:

如果您不想将整数个数作为第一个输入,您可以声明 stack 而不是 array

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

然后您可以使用add 方法添加数字。

【讨论】:

  • 感谢您的提醒。我正在处理一堆堆栈的东西,忘记改变左边的部分。
  • 确实如此,但问题是“编写一个将可变数量的整数作为输入的方法”。该程序只需要 10. 希望使用 (int...a) 语法重写。
  • 您只需将它们添加为堆栈,当您调用int...a 方法时,您会从stack 转换为array
【解决方案3】:

这是一种获取尽可能多的变量的方法并遍历它们:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多