java 参数中输入不同数量的值

java 参数中输入不同数量的值

 1 /**
 2  * 可变长的参数。
 3  * 有时候,我们传入到方法的参数的个数是不固定的,为了解决这个问题,我们一般采用下面的方法:
 4  * 1.  重载,多重载几个方法,尽可能的满足参数的个数。显然这不是什么好办法。
 5  * 2.  将参数作为一个数组传入。虽然这样我们只需一个方法即可,但是,
 6  * 为了传递这个数组,我们需要先声明一个数组,然后将参数一个一个加到数组中。
 7  * 现在,我们可以使用可变长参数解决这个问题,
 8  * 也就是使用...将参数声明成可变长参数。显然,可变长参数必须是最后一个参数。
 9  */
10 public class VarArgs {
11  
12     /**
13      * 打印消息,消息数量可以任意多
14      * @param debug 是否debug模式
15      * @param msgs  待打印的消息
16      */
17     public static void printMsg(boolean debug, String ... msgs){
18         if (debug){
19             // 打印消息的长度
20             System.out.println("DEBUG: 待打印消息的个数为" + msgs.length);
21         }
22         for (String s : msgs){
23             System.out.println(s);
24         }
25         if (debug){
26             // 打印消息的长度
27             System.out.println("DEBUG: 打印消息结束");
28         }
29     }
30     /**
31      * 重载printMsg方法,将第一个参数类型该为int
32      * @param debugMode 是否debug模式
33      * @param msgs  待打印的消息
34      */
35     public static void printMsg(int debugMode, String ... msgs){
36         if (debugMode != 0){
37             // 打印消息的长度
38             System.out.println("DEBUG: 待打印消息的个数为" + msgs.length);
39         }
40         for (String s : msgs){
41             System.out.println(s);
42         }
43         if (debugMode != 0){
44             // 打印消息的长度
45             System.out.println("DEBUG: 打印消息结束");
46         }
47     }
48      
49     public static void main(String[] args) {
50         // 调用printMsg(boolean debug, String ... msgs)方法
51         VarArgs.printMsg(true);
52         VarArgs.printMsg(false, "第一条消息", "这是第二条");
53         VarArgs.printMsg(true, "第一条", "第二条", "这是第三条");
54          
55         // 调用printMsg(int debugMode, String ... msgs)方法
56         VarArgs.printMsg(1, "The first message", "The second message");
57     }
58 }
【做一朵向日葵,面朝太阳,心纳阳光。心,只要有了充盈的阳光,就不再那么的冰;人,也就不再那么的冷;拥有了热度,心也跟着有了温度。】
原文地址:https://www.cnblogs.com/walkingcamel/p/11194984.html