简体   繁体   English

返回私有静态变量

[英]returning a private static variable

I am having trouble returning my static private variable personCount. 我在返回静态私有变量personCount时遇到麻烦。 This variable simply counts the amount of people i add into my program, in my constructor for Person i set it so every time a person was entered, personCount incremented by 1. I have also created a getPersonCount method which simply returns the int value of personCount. 这个变量只是计算我添加到程序中的人数,在我的Person构造函数中将其设置为每输入一个人,personCount就会递增1。我还创建了一个getPersonCount方法,该方法只返回personCount的int值。 。

My problem is that when trying to implement this method in my test file, I am unsure on how to call the method, and get the value of personCount logged to the output. 我的问题是,当尝试在测试文件中实现此方法时,我不确定如何调用该方法,以及如何将personCount的值记录到输出中。

I'm not sure if i am a million miles away or a small syntax error away, so any help would be much appreciated! 我不确定我是在一百万英里之外还是一个小的语法错误,所以我们将不胜感激!

My Person constructor: 我的人构造函数:

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;
} 

My getPersonCount method: 我的getPersonCount方法:

public int getPersonCount()
        {
            return personCount;
        }

My attempt to call the method in my test drive: 我尝试在测试驱动器中调用该方法:

    System.out.println(getPersonCount());

Please let me know if any more code is needed. 请让我知道是否需要更多代码。

Try this, make your method definition in class Person like: 试试这个,在类Person中使您的方法定义像:

public static int getPersonCount() { //<-- note the static modifier
   return personCount;
}

To invoke it: 调用它:

System.out.println(Person.getPersonCount());//<-- use class name, if your using this method outside the class

You have two choices: 您有两种选择:

public static int getPersonCount() { 
   return personCount;
}

with the corresponding call: 与相应的调用:

Person.getPersonCount();

OR :

public int getPersonCount() { 
   return personCount;
}

and the corresponding call: 以及相应的调用:

myPersonInstance.getPersonCount();

So in the last case, you deal with a Person instance. 因此,在最后一种情况下,您要处理一个Person实例。

public static int getPersonCount(){
      return personCount;
}

Then invoke above method 然后调用上面的方法

Person.getPersonCount();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM