0

プログラムについていくつか質問があります。ユーザー入力 (eng) を受け取り、それをモールス符号に変換する Java GUI プログラムを作成しようとしています。入力の文字を一度に 1 文字ずつ調べる必要があります。どうすればいいですか?これには 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);
        }
     });
4

2 に答える 2

2

文字列内のすべての文字を for ループで反復処理します。StringBuilderからへの変換の場合String: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();
}
于 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 をmcString に変換するには、次を使用します。StringBuilder#toString()

于 2015-06-02T00:02:47.127 に答える