我正在为我的高中计算机科学课做一个项目,但我感到有些困惑。我被指示编写一个程序,该程序将用户输入的消息从英语翻译为莫尔斯电码。我已经完成了大部分工作,但似乎无法弄清楚如何将用户的消息实际转换为莫尔斯电码。

import java.util.*;
import java.io.File;
import java.io.IOException;
public class MorseCode
{
public MorseCode()
{

}

//Reads in file containing Morse code and stores into an array of Strings
public static String [] readFile() throws IOException
{
    String [] codes = new String[36];
    int index = 0;
    Scanner fileScanner = new Scanner(new File("morsecode.txt"));

    while( fileScanner.hasNextLine() )
    {
        codes[index] = fileScanner.nextLine();
        index++;
    }

    return codes;
}

//Converts the array of morse codes to an array of its corresponding letter
public static String [] findChars(String [] morseCode)
{
    String [] alphabet = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
                          "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};

    for( int index = 0; index < morseCode.length; index++)
    {
        morseCode[index] = alphabet[index];
    }

    return morseCode;
}
}


主要

截至目前,仅用于测试以确保一切正常。莫尔斯电码及其等效的字母和数字均可正确输出。

import java.util.*;
import java.io.File;
import java.io.IOException;
public class MorseCodeTester
{
public static void main(String [] args) throws IOException
{
    Scanner in = new Scanner(System.in);
    //Original Morse Code
    String [] morseCode = MorseCode.readFile();

    //Conversion to standard english letters
    String [] toConvert = MorseCode.readFile();
    String [] codeToLetters = MorseCode.findChars(toConvert);

    for( int index = 0; index < morseCode.length; index++)
    {
        System.out.println(morseCode[index]);
    }

    System.out.println();

    for( int index = 0; index < morseCode.length; index++)
    {
        System.out.println(codeToLetters[index]);
    }
}
}


如前所述,在用户输入所需的消息后,我的困惑来自英语到莫尔斯电码的实际转换。如果有人能指出我正确的方向,将不胜感激。

最佳答案

您可以将每个字符及其对应的摩尔斯电码字符串存储在Map中。例如

HashMap<String, String> codes = new HashMap<String, String>();
codes.put("a", ".-");
codes.put("b", "-...");


然后,在转换字符串时,您可以使用地图为要转换的字符串的每个字符找到相应的摩尔斯电码字符串。

例如:

String str = "To be converted to morse";
StringBuilder morseSB = new StringBuilder();
for(int i=0; i< str.length(); i++)
{
    morseSB.append(codes.get(Character.toString(str.charAt(i)).toLowerCase()));
}

String morseResult = morseSB.toString();


注意:您将需要添加一些预防性检查。例如检查code.get()的结果是否为null,并且您可能需要处理其他字符,例如空格和句点。

10-08 14:01