static靜態方法的使用

月映荼蘼發表於2024-10-08

測試類,用來執行程式碼
`import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int[] a={4,5,3,6,8,1};//自己初始化陣列
int[] b=new int[10];//自行輸入陣列數字
Scanner scanner=new Scanner(System.in);
int i=0;
//輸入陣列b中內容,直至輸入0退出
while(true){
System.out.println("請輸入一個數字,輸入0退出");
b[i]=scanner.nextInt();
if(b[i]==0)
{
break;
}
i++;
}
//呼叫靜態方法執行相應功能
ArrUtill.arrPrint(a);
int sum1=ArrUtill.getSum(a);
int sum2=ArrUtill.getSum(b);
System.out.println("求和為:"+sum1);
System.out.println(sum2);
Student.teacherName="sayuri";
Student s1=new Student("asuka",19,"w");
ArrUtill.objectPrint(s1);
}

}`

建立一個學生類,定義學生資訊

public class Student {
private String name;
private int age;
private String gender;
static String teacherName;
public Student(){

}
public Student(String name,int age,String gende){
    this.name=name;
    this.age=age;
    this.gender=gende;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}
public void setGender(String gender){
    this.gender=gender;
}
public String getGender(){
    return gender;
}

}

建立自己需要的靜態方法
package homework;

`public class ArrUtill {
private ArrUtill(){}//設定為私有

//輸出整數陣列的靜態方法
public static void arrPrint(int[] arr){
    for (int j : arr) {
        System.out.print(j+" ");
    }
    System.out.println();
}

//求和的靜態方法
public static int getSum(int[] arr){
    int sum=0;
    for(int j : arr){
        sum+=j;
    }
    return sum;
}

//輸出學生物件內容的靜態方法
public static void objectPrint(Student student){
    String name=student.getName();
    int stuAge= student.getAge();
    String gender=student.getGender();
    System.out.print(name+" ");
    System.out.print(stuAge+" ");
    System.out.println(gender);
}

}`

相關文章