zoukankan      html  css  js  c++  java
  • Java可变参数/可变长参数

    Java可变参数/可变长参数


    传递的参数不确定长度,是变长的参数,例如小例子:

    package demo;
    
    public class Demo {
    
    	public static int sum(int n, int... nums) {
    		for (int i = 0; i < nums.length; i++) {
    			n = n + nums[i];
    		}
    
    		return n;
    	}
    
    	public static void main(String[] args) {
    		int s1 = sum(1, 2);
    		int s2 = sum(1, 2, 3);
    		int s3 = sum(1, 2, 3, 4);
    		int s4 = sum(1, 2, 3, 4, 5);
    		
    		System.out.println(s1);
    		System.out.println(s2);
    		System.out.println(s3);
    		System.out.println(s4);
    	}
    }
    

    运行结果:

    3
    6
    10
    15



    注意:必须把变长参数作为最后一个参数传递过去。

  • 相关阅读:
    such用法
    divorce用法
    towel用法
    go for用法
    catch on用法
    incredibly用法
    mess用法
    dentist用法
    steer clear of用法
    incredible
  • 原文地址:https://www.cnblogs.com/hehehaha/p/6147244.html
Copyright © 2011-2022 走看看