java可变参数

本文介绍了Java中的可变参数特性,展示了如何在同一个类中定义同名但参数数量不同的方法。通过可变参数,我们可以创建一个接受0到多个参数的方法,如计算多个数字的总和。示例代码中,`HspMethod`类的`sum`方法能够计算任意数量数字的和,并在`main`方法中进行了调用。此外,还提供了一个`showScore`方法,用于显示学生多门课程的总成绩。
摘要由CSDN通过智能技术生成

基本概念

java 允许将同一个类中多个同名同功能但参数个数不同的方法,封装成一个方法。

就可以通过可变参数实现

基本语法

访问修饰符 返回类型 方法名(数据类型... 形参名) {

}

 //可以计算 2 个数的和,3 个数的和 , 4. 5, 。。
 public class Test3 {
     public static void main(String[] args){
         HspMethod n = new HspMethod();
         System.out.println(n.sum(50 , 60 , 99));
         System.out.println(n.sum(50 , 60 , 56 , 88 , 174));
     }
 }
 class HspMethod{
     public int sum(int... nums){        //int... 表示可以接受0-多个参数
         int res = 0;
         for (int i = 0 ; i < nums.length ; i++){
             res += nums[i];
         }
         return res;
     }
 }
 ​

注意事项

 

练习

 ​
 public class Test3 {
     public static void main(String[] args){
        HspMethod n = new HspMethod();
         System.out.println(n.showScore("蔡徐坤" , 66 , 56 , 76 , 46));
     }
 }
 class HspMethod{
     public String showScore(String name , double... scores){
         double sum = 0;
         for (int i = 0 ; i < scores.length ; i++){
             sum += scores[i];
         }
         return name + scores.length + "门课的总成绩为:" + sum;
     }
 }
 ​
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值