有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计数将参数传递给方法

在java中是否有可能计算传递到方法中的参数数量

有这样的东西:

public class practise7 {

public static void main(String[] args) {

        int[] array3 = new int[]{1};
        int[] array4 = new int[]{1, 3, 4};
        int[] array5 = new int[]{2, 3,};

        combine(array3, array4, array5);
        
    }
   
    public static void combine(int[] array3, int[] array4, int[] array5) {
        //Here i need the number of passed arguments (here 3 e.g.)

        int count = args.length; //found this on google but didn't worked
        System.out.println(count);
        
    }
}

非常感谢


共 (2) 个答案

  1. # 1 楼答案

    试试这个。它使用变量。。。arg语法

    public static void main(String[] args) {
    
            int[] array3 = new int[]{1};
            int[] array4 = new int[]{1, 3, 4};
            int[] array5 = new int[]{2, 3,};
    
            combine(array3, array4, array5);
            
        }
       // uses the variable arguments syntax
        public static void combine(int[]...v) {
            //Here i need the number of passed arguments (here 3 e.g.)
    
            int count = v.length; 
            System.out.println(count);
    
            for (int[] k : v) {
              System.out.println(Arrays.toString(k));
            }
        }
    }
    

    印刷品

    3
    [1]
    [1, 3, 4]
    [2, 3]
    

    请注意,在参数列表中组合数组和非数组有时会产生意外的结果。变量语法参数必须是签名中的最后一个参数

  2. # 2 楼答案

    您的解决方案不起作用,因为使用了args。length'您只能获取在主函数中传递的参数数。您可以使用Java的variable Arumges功能,如下所示:

    public static void combine(int[] ... arrays) 
    {
            int count = arrays.length;
            System.out.println(count);
    }