从另一个类打印Java的静态变量

huangapple go评论68阅读模式
英文:

Print java static variable from another class

问题

以下是翻译好的部分:

我想要打印另一个类的静态变量,但由于某些原因我无法做到。以下是编译时出现的错误:

System.out.println(Creature.MAX_Y);
                               ^
  符号   变量 MAX_Y
  位置 类 Creature
1 个错误

这是 Creature 类的代码:

package naturalselection.creature;

import naturalselection.food.Food;
import naturalselection.vector.Vector;
import naturalselection.creature.Target;
import java.util.*;
public class Creature{
  public static short MAX_X = 150;
  public static short MAX_Y = 150;
}

以及主类:

import naturalselection.creature.Creature;
import naturalselection.food.Food;

class Main{
  public static void main(String[] args){
    Creature c1 = new Creature(1, 1);
    System.out.println(Creature.MAX_Y);
  }
}

以下是目录结构的一部分:

main.java
naturalselection -
+-- creature
    +-- Creature.java
英文:

I would like to print the static variable of another class but I cant for some reason. Here is the error when compiling:

System.out.println(Creature.MAX_Y);
                               ^
  symbol:   variable MAX_Y
  location: class Creature
1 error

Here is the code for the Creature class:

package naturalselection.creature;

import naturalselection.food.Food;
import naturalselection.vector.Vector;
import naturalselection.creature.Target;
import java.util.*;
public class Creature{
  public static short MAX_X = 150;
  public static short MAX_Y = 150;
}

and the main class:

import naturalselection.creature.Creature;
import naturalselection.food.Food;

class Main{
  public static void main(String[] args){
    Creature c1 = new Creature(1, 1);
    System.out.println(Creature.MAX_Y);
  }
}

Here is the directory structure (part of it):

main.java
naturalselection -
+-- creature
    +-- Creature.java

答案1

得分: 1

你需要在试图获取变量的那个类中声明静态变量。\n public static String variableName = "Value";

英文:

You need to declare static variable in that class from where you are trying to get variable.
public static String variableName = "Value";

huangapple
  • 本文由 发表于 2020年7月27日 02:13:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63103949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定