0

I have a load of images of musical symbols which I need to do some processing on and for each one I need to get the integer code corresponding to its file name. There are 23 possible file name strings and 23 integer code and there are many images with the same name under different directories.

The solution I have so far is given (abbreviated) below. I have just defined a load of int and String constants and then written a method which is just a huge chain of if statements to do the translation.

What would be a better way to achieve the same effect? The way I've done it seems really awful! I thought about using some kind of Map, but I wasn't sure of the best way to do so.

public class Symbol {
    public static final int TREBLE_CLEF = 0;
    public static final int BASS_CLEF = 1;
    public static final int SEMIBREVE = 2;
    // ...

    public static final String S_TREBLE_CLEF = "treble-clef";
    public static final String S_BASS_CLEF = "bass-clef";
    public static final String S_SEMIBREVE = "semibreve";
    // ...

    public static int stringCodeToIntCode(String strCode) {
        if (strCode == S_TREBLE_CLEF) {
            return TREBLE_CLEF;
        } else if (strCode == S_BASS_CLEF) {
            return BASS_CLEF;
        } else if (strCode == S_SEMIBREVE) {
            return SEMIBREVE;
        } //...

        else {
            return -1;
        }
    }
}
Max Spencer
  • 1,701
  • 2
  • 12
  • 21
  • 2
    as the answers say, use an enum. Also it is bad practice to compare Strings with `==`, always use `equals`, for more info, see [this post](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – jlordo Dec 14 '12 at 16:28

3 Answers3

5

I think you are looking for Enum where you can have String constant and its value.

Example:

public enum YourEnumClass{
    STRING_CONST (5),
    STRING_CONST2 (7),
    .....
     //constructor
     //getValue() method
}

read linked tutorial for more details.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • But doesn't that only enable me to go from an instance of `YourEnumClass` to the corresponding `int` code? How do I get from a `String` like `"treble-clef"` to the right enum type? – Max Spencer Dec 14 '12 at 17:07
  • I guess in Enum class you can have your own logic to reverse lookup, see this http://stackoverflow.com/questions/5316311/java-enum-reverse-look-up-best-practice. – kosa Dec 14 '12 at 17:08
1
enum StringToInt{
  TREBLE_CLEF(0),

  ......
}

Enum is the way to go.

Another example:

public enum Color {
 WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

 private int code;

 private Color(int c) {
   code = c;
 }

 public int getCode() {
   return code;
 }
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
0

how about a hashmap

HashMap<String,Integer> hm=new HashMap<String,Integer();
hm.put("treble-clef",0);
//rest

and get it by using this

int value=hm.get("treble-clef");
Bhavik Shah
  • 5,125
  • 3
  • 23
  • 40