/Users/petercappello/NetBeansProjects/56-2014/56-2014-lab5/src/Main.java

/**
 * Encode an English-language phrase as Morse code.
 * @author Peter Cappello
 */
public class Main 
{
    private static final String[] letterToCode = 
    {
        ".-",
        "-...",
        "_._.",
        "-..",
        ".", // E
        ".._.",
        "--.", // G
        "....",
        "..",
        ".---",
        "-.-",
        ".-..",
        "--", // M
        "_.",
        "---",
        ".--.",
        "--.-",
        "._.",
        "...", // S
        "-",
        ".._", // U
        "...-",
        ".--", // W
        "-..-",
        "-.--",
        "--.."
    };
    
    private static final String[] digitToCode = 
    {
        "-----", // 0
        ".----",
        "..---",
        "...--",
        "....-", // 4
        ".....",
        "-....", // 6
        "--...",
        "---..",
        "----."
    };
    /**
     * Encode a string consisting of upper-case alphabetic words and digits.
     * @param string to be encoded
     * @return Morse code of the string, where there is 1 space between encoded 
     * characters and 3 spaces between encoded words (i.e., consecutive letter/digits).
     * 
     * It probably is better to use Maps. 
     * But, we have not covered Maps yet.
     * Alternatively, switch on each char value.
     * Below, I use a String[] with a simple function of char as the index. 
     * Again, this is reasonable only until we cover Maps.
     */
    public static String encode( String string )
    {
        StringBuilder morseCodedString = new StringBuilder();
        for ( String word : string.split( " " ) )
        {
            for ( char character : word.toCharArray() )
            {
                String code = Character.isAlphabetic( character ) ? letterToCode[ character - 'A' ] : digitToCode[ character - '0' ];
                morseCodedString.append( code ).append( ' ' );
            }
            morseCodedString.append( "   " ); // 3 spaces between coded words
        }
        return morseCodedString.toString();
    }
    
    public static void main( String[] args )
    {
        String test = "THIS IS A TEST TESTING 1 2 3";
        System.out.println( "Morse encoding of '" + test + "'" );
        System.out.println( encode( test ) );
    }
}