package com.demo.day;
/*
java 允许将同一个类中多个同名同功能 但 参数个数不同的方法,封装成一个方法,就可以通过可变参数实现
*/
public class Varparameter {
public static void main(String[] args) {
HspMethod m = new HspMethod();
System.out.println(m.sum(1,4,3,2,4,53,34));
}
}
class HspMethod{
public int sum(int n1,int n2){
return n1 + n2;
}
public int sum(int n1,int n2,int n3){
return n1 + n2 + n3;
}
public int sum(int n1,int n2,int n3,int n4){
return n1 + n2 + n3 + n4;
}
//int... 表示接受的是可变参数,类型是int,即可以接收多个int(0~n)
//使用可变参数时,可以当作数组来使用,即nums可以当作数组
//遍历 nums 求和即可
public int sum(int... nums){
// System.out.println("接收的参数个数=" + nums.length);
int res = 0;
for (int i = 0;i < nums.length;i++){
res += nums[i];
}
return res;
}
//可变参数可以和普通类型的参数一起放在形参列表,但必须保证可变参数是在最后
//一个形参列表中只能有一个可变参数
public void f2(String str,double... nums){
}
}
package com.demo.day;
import java.util.Scanner;
public class VarParameterExercise {
public static void main(String[] args) {
YshMethod ysh = new YshMethod();
Scanner sc = new Scanner(System.in);
System.out.println(ysh.showScore("游书恒",78.5,99,56,56,45,34,65,34,88));
}
}
class YshMethod {
public String showScore(String name,double score1,double score2){
double res = score1 + score2;
return "姓名:" + name + "\n两门总分:" + res;
}
public String showScore(String name,double score1,double score2,double score3){
double res = score1 + score2 + score3;
return "姓名:" + name + "\n三门总分:" + res;
}
public String showScore(String name,double score1,double score2,double score3,double score4,double score5){
double res = score1 + score2 + score3 + score4 + score5;
return "姓名:" + name + "\n五门总分:" + res;
}
public String showScore(String name,double... scores){
double res = 0;
int num = 0;
for (int i = 0;i<scores.length;i++){
res += scores[i];
num++;
}
return "姓名:" + name + "\n" + num + "门总分:" + res;
}
}