0

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);
        }
     });
4

2 回答 2

2

使用 for 循环遍历字符串中的所有字符。对于从StringBuilderto的转换StringStringBuilder.toString()返回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();
}
于 2015-06-01T23:58:25.750 回答
1

对于用户给定的字符串string,您将转换为大写以匹配 HashMap 中的字符,并遍历字符。

for (int i = 0; i < string.length(); i++) {
    String s = charToCode.get(string.charAt(i));
    if (s == null) throw new RuntimeException ("No character found");

    mc.append(s).append(' ');
}

要将 StringBuilder, mc, 转换为字符串,请使用StringBuilder#toString()

于 2015-06-02T00:02:47.127 回答