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

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

Print java static variable from another class

问题

以下是翻译好的部分:

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

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

这是 Creature 类的代码:

  1. package naturalselection.creature;
  2. import naturalselection.food.Food;
  3. import naturalselection.vector.Vector;
  4. import naturalselection.creature.Target;
  5. import java.util.*;
  6. public class Creature{
  7. public static short MAX_X = 150;
  8. public static short MAX_Y = 150;
  9. }

以及主类:

  1. import naturalselection.creature.Creature;
  2. import naturalselection.food.Food;
  3. class Main{
  4. public static void main(String[] args){
  5. Creature c1 = new Creature(1, 1);
  6. System.out.println(Creature.MAX_Y);
  7. }
  8. }

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

  1. main.java
  2. naturalselection -
  3. +-- creature
  4. +-- 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:

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

Here is the code for the Creature class:

  1. package naturalselection.creature;
  2. import naturalselection.food.Food;
  3. import naturalselection.vector.Vector;
  4. import naturalselection.creature.Target;
  5. import java.util.*;
  6. public class Creature{
  7. public static short MAX_X = 150;
  8. public static short MAX_Y = 150;
  9. }

and the main class:

  1. import naturalselection.creature.Creature;
  2. import naturalselection.food.Food;
  3. class Main{
  4. public static void main(String[] args){
  5. Creature c1 = new Creature(1, 1);
  6. System.out.println(Creature.MAX_Y);
  7. }
  8. }

Here is the directory structure (part of it):

  1. main.java
  2. naturalselection -
  3. +-- creature
  4. +-- 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:

确定