1

I'm looking for a way to create a "header" or something like that to specify some variables like:

enum Misc
{
    double EFFECT_DAMAGE = Math.pow(2,0);
    double EFFECT_ABSORB = Math.pow(2,1);
    double EFFECT_HEAL   = Math.pow(2,2);
    int SPELL_FIREBALL   = 51673;
}

And in every .java file I want to be able to write:

double effect = 1;
if (effect == EFFECT)
{
    ...some code...
}

Is there a nice way to do this? I'm creating a mini game for now and want to have all the files nice and tidy to manage my project in the future easier once it gets bigger.

Thx in advance.

Rafael Skubisz
  • 460
  • 3
  • 9
  • 1
    Extend `Application` and put the enum in there. http://stackoverflow.com/questions/4572338/extending-application-to-share-variables-globally – Simon Sep 01 '14 at 13:35
  • Can I know why my answer using Enum as you wished did not satisfy you? – Michael Brenndoerfer Sep 04 '14 at 21:49
  • Your code was nice. I used it first but later I wanted to use the code in a switch and with your code I got a problem that its a bad type and stuff like that and I switched to sergiomse answer and it works good too + it works in switches. – Rafael Skubisz Sep 09 '14 at 09:04

2 Answers2

2
public enum Misc 
{
    EFFECT_DAMAGE(0), // 2^0
    EFFECT_ABSORB(1), // 2^1
    FIREBALL(245151);

    private double value;

    private Misc(double d){
        value = d;
    }

    public String toString(){
        return String.valueOf(value);
    }
}

Access like this:

System.out.println("Fireball damage:" + Misc.FIREBALL);
Michael Brenndoerfer
  • 3,483
  • 2
  • 39
  • 50
1

You cannot assign values this way to a enum in java.

Instead you should use a public class with public static final variables to make them constants.

public class Misc {
    public static final double EFFECT_DAMAGE = Math.pow(2,0);
    public static final double EFFECT_ABSORB = Math.pow(2,1);
    public static final double EFFECT_HEAL   = Math.pow(2,2);
    public static final int SPELL_FIREBALL   = 51673;
}

So you can use in your code like

if (effect == Misc.EFFECT_DAMAGE )
{
    ...some code...
}

If you want use only the field without the class name first you should import the class as static:

import static test.Misc.*;

....

if (effect == EFFECT_DAMAGE ) {
sergiomse
  • 775
  • 12
  • 18