【问题标题】:How do I use a static variable to keep track of highest age如何使用静态变量来跟踪最高年龄
【发布时间】:2019-06-29 20:05:52
【问题描述】:

我目前有一个 Person 类,其中包含创建姓名、年龄、电子邮件和 ssn 以及验证其输入的选项。我将如何使用静态变量来跟踪为 Person 输入的最高年龄?

【问题讨论】:

  • 通过编写代码。你有更具体的问题吗?你试过什么?你被困在哪里了?
  • 每次分配年龄时,应检查年龄是否不超过最高年龄,如果是,则应为最高年龄。 (如果可以减少年龄[不是单调的],那就更难了。)
  • 请向我们展示您的尝试,并提供minimal reproducible example

标签: java variables static


【解决方案1】:

我想你的班级有一个像

这样的方法
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();

【讨论】:

    猜你喜欢
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多