[英]How do I use a static variable to keep track of highest age
我目前有一個 Person 類,可以選擇創建姓名、年齡、電子郵件和 ssn,並驗證他們的輸入。 我將如何使用靜態變量來跟蹤為 Person 輸入的最高年齡?
我想你的班級有一個像
public void setAge(int age){
this.age = age;
}
而你想要得到年齡最大的人。
添加靜態屬性Person,在setAge方法中比較年齡,如果當前人高於上一個或上一個為空,則保存當前
public class Person {
private int age;
// other attrs
// ...
public static Person highest;
public void setAge(int age){
this.age = age;
if (highest == null || this.age > highest.getAge()){
highest = this;
}
}
// getters and setters
}
這樣你就可以得到最高年齡
int highestAge = Person.highest.getAge();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.