I'd suggest adding a comment mentioning how the order of values in the arrays morseChar
and morseNumber
are important for the conversion.
At first glance I was confused how the conversion was being done.
You should declare morseChar
and morseNumber
as final class variables so they are easily visible & can be used in other methods.
If you may add symbols to the code, a class or enum containing the MorseCode and english character can be added. This also makes the opposite conversion very easy.
// Note: Simply add numbers and symbols to this enum.
// The Order does not matters.
public enum MorseCharacter
{
A(".-", 'a'),
B("-...", 'b'),
C("-.-.", 'c'),
D("-..", 'd'),
E(".", 'e'),
F("..-.", 'f'),
G("--.", 'g'),
H("....", 'h'),
I("..", 'i'),
J(".---", 'j'),
K("-.-", 'k'),
L(".-..", 'l'),
M("--", 'm'),
N("-.", 'n'),
O("---", 'o'),
P(".--.", 'p'),
Q("--.-", 'q'),
R(".-.", 'r'),
S("...", 's'),
T("-", 't'),
U("..-", 'u'),
V("...-", 'v'),
W(".--", 'w'),
X("-..-", 'x'),
Y("-.--", 'y'),
Z("--..", 'z');
private String morseCode;
private char asciiCharacter;
MorseCharacter(String morseCode, char asciiCharacter)
{
this.setMorseCode(morseCode);
this.setAsciiCharacter(asciiCharacter);
}
public String getMorseCode()
{
return morseCode;
}
public void setMorseCode(String morseCode)
{
this.morseCode = morseCode;
}
public char getAsciiCharacter()
{
return asciiCharacter;
}
public void setAsciiCharacter(char asciiCharacter)
{
this.asciiCharacter = asciiCharacter;
}
public static MorseCharacter valueOf(char character)
{
for (MorseCharacter morseChar : values())
{
if (morseChar.getAsciiCharacter() == character)
{
return morseChar;
}
}
throw new RuntimeException("Morse character not found: " + character);
}
}
public static String toMorse(String text)
{
String morseText = "";
text = text.toLowerCase();
for (int i = 0; i < text.length(); i++)
{
morseText += MorseCharacter.valueOf(text.charAt(i)).getMorseCode();
}
return morseText;
}