用户界面- Java莫尔斯电码应用程序继续(gui)



我对我的程序有几个问题。我试图创建一个java gui程序,需要用户输入(英文),然后将其转换为莫尔斯电码。我需要遍历输入的字符,一次一个字符。我该怎么做呢?我知道你需要使用charAt(i),但我真的不明白如何将它应用到这个程序。此外,我如何将StringBuilder转换为字符串,放入标签?非常感谢您的宝贵时间。这是我目前所掌握的。

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

使用for循环遍历字符串中的所有字符。从StringBuilderString的转换:StringBuilder.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();
}

对于用户给出的字符串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()

最新更新