Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enumeration of Musical Notes

Tags:

java

enums

How would you create an enumeration of the musical notes in Java, with each notes having an octave and then a keyed variable? This is what I have so far...

    public enum Notes
    {
            c,
            cS,
            d,
            dS,
            e,
            f,
            fS,
            g,
            gS,
            a,
            aS,
            b;
            int octave;
            boolean isPlaying;
    }

So when I access the enums in my code I write something like this...

Notes.c.octave = 4;
Notes.c.isPlaying = true;

Now here is my question: How can I have an isPlaying boolean for each note in each octave?

Like so:

Notes.c.octave.isPlaying = true;

Or would I have to go like:

public enum Notes
{
        c1,
        cS1,
        d1,
        dS1,
        e1,
        f1,
        fS1,
        g1,
        gS1,
        a1,
        aS1,
        b1
        c2,
        cS2,
        d2,
        dS2,
        e2,
        f2,
        fS2,
        g2,
        gS2,
        a2,
        aS2,
        b2;

        etc...

        boolean isPlaying;
}

Thank you in advance for taking your time to answer this question!

like image 839
Crupler Avatar asked Jan 30 '26 18:01

Crupler


1 Answers

You should not modify the fields of your enum!!!

The reason is that each instance is unique in the JVM (like a singleton), and another thread using the same note will be sharing the same playing field, which is a seriously wrong design.

Also, your enum should be named singular Note, not plural Notes. The reason should be obvious: Each instance of the enum represents a single note, not multiple notes.


The right way to do it would be to create a class that has 3 fields:

public class Tone {
    private Note note; 
    private int octave;
    private boolean playing;
    // with getters and setters
}

Since every note can be flat ♭, sharp ♯, double-flat 𝄫 and double-sharp 𝄪, I would use this model which more accurately reflects reality. Also, even the playing field feels wrong. It feels more like Tone should be immutable and some other entity (eg Player) knows what Tones are currently playing, so I'd recommend this:

public enum Note {
    C, D, E, F, G, A, B
}

public enum Shift {
    DoubleFlat, Flat, Natural, Sharp, DoubleSharp
}

public class Tone {
    private Note note; 
    private Shift shift; 
    private int octave;
    private int duration; // include a duration - perhaps milliseconds
    // with only getters, being immutable
}

public class Player {
    // has references to `Tones` and a way to schedule their being played
}
like image 58
Bohemian Avatar answered Feb 01 '26 07:02

Bohemian