The name of the key is a half step ABOVE the last sharp in the key.
Using A as an example, it has 3 sharps (F#, C#, G#). The last sharp is G#. A half step from there is A.
The tune is in A.
The name of the key is the next to LAST flat in the key.
Using Eb as an example, it has 3 flats (Bb, Eb, Ab). The next to last flat is Eb.
The tune is in Eb.
An exception to flats is that the key of F only has one flat (Bb). So, there is no next to last flat.
The key of C has no sharps or flats.