Teaching yourself Java by coding a MIDI processing program. One thing the program needs to do is convert between MIDI note numbers and corresponding compact string representations. I looked at using enum setup, but due to name restrictions you cannot do something like
c-1, c
because of sharp objects and negatives (yes, I follow the agreement, as a result of which you get a negative octave: P).
It seemed awkward to make a conversion between what is allowed and what I want.
CNEG1("c-1"),
CSNEG1("c#-1"),
DNEG1("d-1"),
...
G9("g9");
So, I came up with a static import scheme below, and it works fine. However, I want to learn more about how to use enumerations, and I have a hunch that they really can be somehow better suited for this task - if I had a better understanding of all the inputs and outputs. So my question is: can anyone come up with an elegant way to provide the same functionality using the enum scheme? Moreover, will there be a valid argument for this?
public abstract class MethodsAndConstants {
public static final String TONICS[] = {"c","c#","d","d#","e","f","f#","g","g#","a","a#","b"};
static final NoteMap notemap = new NoteMap();
static class NoteMap{
static String map[] = new String[128];
NoteMap() {
for (int i = 0; i < 128; i++){
int octave = i/12 - 1;
String tonic = MethodsAndConstants.TONICS[i%12];
map[i] = tonic + octave;
}
}
}
public static int convert_midi_note(String name){
return indexOf(NoteMap.map, name);
}
public static String convert_midi_note(int note_num){
return NoteMap.map[note_num];
}
public static int indexOf(String[] a, String item){
return java.util.Arrays.asList(a).indexOf(item);
}
}
EDIT ------------------------------------------
After hard consideration, I think that in this particular situation, the transfers may be overwhelming in the end. I could just use this code here, the same approach to static import, but no longer requiring anything like the NoteMap case above.
note_num → , → note_num - .
public abstract class MethodsAndConstants {
public static final String[] TONICS = {"c","c#","d","d#","e","f","f#","g","g#","a","a#","b"};
static String convert(int i) {
String tonic = MethodsAndConstants.TONICS[i%12];
int octave = (i / 12) - 1;
return tonic + octave;
}
static int convert(String s) {
int tonic = java.util.Arrays.asList(MethodsAndConstants.TONICS).indexOf(s.substring(0,1));
if (s.contains("#")) tonic += 1;
int octave = Integer.parseInt(s.substring(s.length()-1));
if (s.contains("-")) octave -= 2;
int note_num = ((octave + 1) * 12) + tonic;
return note_num;
}
}