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){
}
}
![image-20230513210822639]()
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;
}
}