[英]returning a private static variable
我在返回靜態私有變量personCount時遇到麻煩。 這個變量只是計算我添加到程序中的人數,在我的Person構造函數中將其設置為每輸入一個人,personCount就會遞增1。我還創建了一個getPersonCount方法,該方法只返回personCount的int值。 。
我的問題是,當嘗試在測試文件中實現此方法時,我不確定如何調用該方法,以及如何將personCount的值記錄到輸出中。
我不確定我是在一百萬英里之外還是一個小的語法錯誤,所以我們將不勝感激!
我的人構造函數:
public Person(String foreName, String surName, int age,
double height, String gender)
{
this.foreName = foreName;
this.surName = surName;
this.age = age;
this.height = height;
this.gender = gender;
personCount = personCount +1;
}
我的getPersonCount方法:
public int getPersonCount()
{
return personCount;
}
我嘗試在測試驅動器中調用該方法:
System.out.println(getPersonCount());
請讓我知道是否需要更多代碼。
試試這個,在類Person中使您的方法定義像:
public static int getPersonCount() { //<-- note the static modifier
return personCount;
}
調用它:
System.out.println(Person.getPersonCount());//<-- use class name, if your using this method outside the class
您有兩種選擇:
public static int getPersonCount() {
return personCount;
}
與相應的調用:
Person.getPersonCount();
或 :
public int getPersonCount() {
return personCount;
}
以及相應的調用:
myPersonInstance.getPersonCount();
因此,在最后一種情況下,您要處理一個Person
實例。
public static int getPersonCount(){
return personCount;
}
然后調用上面的方法
Person.getPersonCount();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.