Search code examples
javauser-interfacemorse-code

Java morse code application continued (gui)


i have a couple questions about my program. I am attempting to create a java gui program that takes the user input (eng) and then translate it to morse code. I need to go through characters of the input one characters at a time. How do i do this? i know you need to use charAt(i) for this but i really don't understand how to apply it to this program. Also, how do i convert StringBuilder to string, to put in the label? thanks a lot for your time. heres what i have so far.

    Map<Character,String> charToCode = new HashMap<Character,String>();
    charToCode.put('A', ".-");
    charToCode.put('B', "-...");
    charToCode.put('C', "-.-.");
    charToCode.put('D', "-..");
    charToCode.put('E', ".");
    charToCode.put('F', "..-.");
    charToCode.put('G', "--.");
    charToCode.put('H', "....");
    charToCode.put('I', "....");
    charToCode.put('J', ".---");
    charToCode.put('K', "-.-");
    charToCode.put('L', ".-..");
    charToCode.put('M', "--");
    charToCode.put('N', "-.");
    charToCode.put('O', "---");
    charToCode.put('P', ".--.");
    charToCode.put('Q', "--.-");
    charToCode.put('R', ".-.");
    charToCode.put('S', "...");
    charToCode.put('T', "-");
    charToCode.put('U', "..-");
    charToCode.put('V', "...-");
    charToCode.put('W', "..-");
    charToCode.put('X', "-..-");
    charToCode.put('Y', "-.--");
    charToCode.put('Z', "--..");




   text1.addActionListener(new ActionListener()
    {
     public void actionPerformed(ActionEvent e)
     {
       String input = text2.getText();
       label.setText(input);
     }
   });

     button.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
        String input = text1.getText();
        label.setText(charToCode);
        }
     });

Solution

  • Iterate over all characters in the string with a for-loop. For the conversion from StringBuilder to String: StringBuilder.toString() returns the content of the StringBuilder.

    public String parseCode(Map<Character , String> morseAlphabet , String input){
        StringBuilder morse = new StringBuilder();
    
        //iterate over the indices of all characters in range
        for(int i = 0 ; i < input.length() ; i++)
            if(morseAlphabet.get(input.charAt(i)) == null)
                //the character has no valid representation in morse-alphabet
                throw new IllegalArgumentException("unknown sign: \\u" + (int) input.charAt(i));
            else
                //append the correct morsesign to the output
                morse.append(morseAlphabet.get(input.charAt(i)));
    
        return morse.toString();
    }