3

我想构建一个将英语翻译成摩尔斯电码的程序,反之亦然,我决定使用哈希映射来做到这一点,但我不确定如何通过哈希映射运行字符串并在结束。这是我目前的代码:

import java.util.HashMap;
import java.util.Map;

public class MorseCodeTranslator{

public static String translateToMorseCode() {
    String englishtoMorse = "";
    String translation = null;

    Map<Character, String> morse = new HashMap<Character, String>();
    morse.put('a', "._");
    morse.put('b', "_...");
    morse.put('c',  "_._");
    morse.put('d',  "_..");
    morse.put('e',    ".");
    morse.put('f', ".._.");
    morse.put('g',  "__.");
    morse.put('h', "....");
    morse.put('i',   "..");
    morse.put('j', ".___");
    morse.put('k',   "_.");
    morse.put('l', "._..");
    morse.put('m',   "__");
    morse.put('n',   "_.");
    morse.put('o',  "___");
    morse.put('p', ".__.");
    morse.put('q', "__._");
    morse.put('r', "._.");
    morse.put('s',  "...");
    morse.put('t',   "_");
    morse.put('u',  ".._");
    morse.put('v', "..._");
    morse.put('w',  ".__");
    morse.put('x', "_.._");
    morse.put('y', "_.__");
    morse.put('z', "__..");

    return translation;
}    

public static String translateFromMorseCode() {
    String morsetoEnglish = "";
    String translation = null;

    Map<Character, String> morse = new HashMap<Character, String>();
    morse.put('a', "._");
    morse.put('b', "_...");
    morse.put('c',  "_._");
    morse.put('d',  "_..");
    morse.put('e',    ".");
    morse.put('f', ".._.");
    morse.put('g',  "__.");
    morse.put('h', "....");
    morse.put('i',   "..");
    morse.put('j', ".___");
    morse.put('k',   "_.");
    morse.put('l', "._..");
    morse.put('m',   "__");
    morse.put('n',   "_.");
    morse.put('o',  "___");
    morse.put('p', ".__.");
    morse.put('q', "__._");
    morse.put('r', "._.");
    morse.put('s',  "...");
    morse.put('t',   "_");
    morse.put('u',  ".._");
    morse.put('v', "..._");
    morse.put('w',  ".__");
    morse.put('x', "_.._");
    morse.put('y', "_.__");
    morse.put('z', "__..");  

    return translation;
}
}  

我希望能够运行哈希映射中englishtoMorsemorsetoEnglish通过哈希映射的任何内容,并将字符转换为与哈希映射关联的值,然后将它们输出到translation.

4

6 回答 6

3

将地图创建为静态字段。添加莫尔斯字母表。然后创建一个方法,将要翻译的文本作为参数。然后迭代文本以翻译每个字符并使用翻译的字符创建将返回的字符串。

我用你的代码和我的解释做了一个例子。该代码仅适用于莫尔斯的英文文本。您必须添加另一个方向。

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{

    private static final Map<Character, String> morse = new HashMap<Character, String>();
    static {
    morse.put('a', "._");
    morse.put('b', "_...");
    morse.put('c',  "_._");
    morse.put('d',  "_..");
    morse.put('e',    ".");
    morse.put('f', ".._.");
    morse.put('g',  "__.");
    morse.put('h', "....");
    morse.put('i',   "..");
    morse.put('j', ".___");
    morse.put('k',   "_.");
    morse.put('l', "._..");
    morse.put('m',   "__");
    morse.put('n',   "_.");
    morse.put('o',  "___");
    morse.put('p', ".__.");
    morse.put('q', "__._");
    morse.put('r', "._.");
    morse.put('s',  "...");
    morse.put('t',   "_");
    morse.put('u',  ".._");
    morse.put('v', "..._");
    morse.put('w',  ".__");
    morse.put('x', "_.._");
    morse.put('y', "_.__");
    morse.put('z', "__..");
    morse.put(' ', " ");
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        String str = "Hello World";
        System.out.println(translate(str));
    }



    public static String translate(String text) {
        StringBuilder builder = new StringBuilder();
        String lower = text.toLowerCase();
        for (int i = 0; i < text.length(); i++) {
            builder.append(morse.get(lower.charAt(i)));
        }
        return builder.toString();
    }    

}

输出:

......_..._..___ ._____._.._.._..

工作示例:

http://ideone.com/uWGatU

于 2015-11-20T13:15:06.823 回答
1

至于“English to Morse”用例,使用这样的for循环:

StringBuilder sb = new StringBuilder();
for ( int i = 0; i < englishtoMorse.length(); i++) {
    char c = englishtoMorse.charAt(i);
    sb.append(morse.get(c));
}
translate = sb.toString();

至于“莫尔斯到英语”用例,您需要在莫尔斯字符之间使用某种分隔符。否则你会得到一个只包含“e”和“t”的翻译。假设,您的morseToEnglish字符串在字符之间使用空格作为分隔符。然后你可以像这样进行翻译:

StringTokenizer st = new StringTokenizer(morseToEnglish);
StringBuilder result = new StringBuilder();
while( st.hasMoreTokens()) {
    result.append(morse.findKey(st.nextToken()));
}
translation = sb.toString();

我希望这会有所帮助。

于 2015-11-20T13:19:28.180 回答
1

您应该初始化地图一次(例如,在静态数据成员中,如 Zelldon 建议的那样)。完成此操作后,可以使用 Java 8 的流 API 非常优雅地将字符串从英语翻译成莫尔斯语:

public static String translateToMorseCode(String english) {
    return english.chars()
                  .boxed()
                  .map(c -> morse.get((char) c.intValue()))
                  .collect(Collectors.joining());
}

编辑:
正如 JB Nizet 评论的那样,使用mapToObj会更优雅(并且可能更有效):

public static String translateToMorseCode(String english) {
    return english.chars()
                  .mapToObj(c -> morse.get((char) c))
                  .collect(Collectors.joining());
}
于 2015-11-20T13:23:16.713 回答
0

使用一个表并使用 Map.entrySet() 进行向后搜索。并且不要忘记分隔符。

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

public class MorseCodeTranslator{
    public static Map<Character, String> getMorseTable(){
        Map<Character, String> morse = new HashMap<Character, String>();
        morse.put('a', "._");
        morse.put('b', "_...");
        morse.put('c',  "_._");
        morse.put('d',  "_..");
        morse.put('e',    ".");
        morse.put('f', ".._.");
        morse.put('g',  "__.");
        morse.put('h', "....");
        morse.put('i',   "..");
        morse.put('j', ".___");
        morse.put('k',   "_.");
        morse.put('l', "._..");
        morse.put('m',   "__");
        morse.put('n',   "_.");
        morse.put('o',  "___");
        morse.put('p', ".__.");
        morse.put('q', "__._");
        morse.put('r', "._.");
        morse.put('s',  "...");
        morse.put('t',   "_");
        morse.put('u',  ".._");
        morse.put('v', "..._");
        morse.put('w',  ".__");
        morse.put('x', "_.._");
        morse.put('y', "_.__");
        morse.put('z', "__..");
        return morse;
    }
    public static String toMorse(String text){      
        Map<Character, String> table  = getMorseTable();
        StringBuilder result = new StringBuilder();
        // get every char in text
        for(int i = 0; i < text.length(); i++){
            char c = text.charAt(i);
            // and add morse character from table
            result.append(table.get(c));
            // put character separator
            result.append("|");
        }
        // delete last character separator
        result.deleteCharAt(result.length() - 1);
        return result.toString();
    }

    public static String fromMorse(String morse){
        Map<Character, String> table  = getMorseTable();
        // use string tokenizer to separate morse characters
        StringTokenizer st = new StringTokenizer(morse,"|");
        StringBuilder result = new StringBuilder();
        // get every morse character
        while( st.hasMoreTokens()) {
            String morseChar = st.nextToken();
            // and find equivalent letter in morse table
            for (Entry<Character, String> entry : table.entrySet()) {
                if (entry.getValue().equals(morseChar)) {
                   result.append(entry.getKey());
                   break;
                }
            }
        }
        return result.toString();
    }

    public static void main(String[] args){
        String text = "abcxyz";
        System.out.println(text);
        String morse = toMorse(text);
        System.out.println(morse);
        String back = fromMorse(morse);
        System.out.println(back);
    }
}

输出:

abcxyz
._|_...|_._|_.._|_.__|__..
abcxyz
于 2015-11-20T13:48:09.970 回答
0

你可以在BiMap这里使用。我认为它更适合您的情况。

BiMap<Character, String> biMap = HashBiMap.create();

biMap.put('a', "._");
biMap.put('b', "_..");

System.out.println("morse code = " + biMap.get('a'));
System.out.println("alphabet = " + biMap.inverse().get("._"));

您可以使用guava。访问链接

于 2015-11-20T13:10:58.300 回答
0

您可以根据需要使用 HashMap:

    import java.util.HashMap;
    import java.util.Map;

    public class MorseCodeTranslator{
    public static Map<Character, String> morse = new HashMap<Character, String>();
    public static Map<String, Character> english = new HashMap<>();
    public MorseCodeTranslator(){
    morse.put('a', "._");
    morse.put('b', "_...");
    morse.put('c',  "_._");
    morse.put('d',  "_..");
    morse.put('e',    ".");
    morse.put('f', ".._.");
    morse.put('g',  "__.");
    morse.put('h', "....");
    morse.put('i',   "..");
    morse.put('j', ".___");
    morse.put('k',   "_.");
    morse.put('l', "._..");
    morse.put('m',   "__");
    morse.put('n',   "_.");
    morse.put('o',  "___");
    morse.put('p', ".__.");
    morse.put('q', "__._");
    morse.put('r', "._.");
    morse.put('s',  "...");
    morse.put('t',   "_");
    morse.put('u',  ".._");
    morse.put('v', "..._");
    morse.put('w',  ".__");
    morse.put('x', "_.._");
    morse.put('y', "_.__");
    morse.put('z', "__..");
    morse.forEach( (c,s) -> english.put(s, c));
    }


    public static String translateToMorseCode(final String english) {
    char[] data = english.toCharArray();
    StringBuilder result = new StringBuilder();
    for(char c: data) result.append(morse.get(new Character(c)));
    return result.toString();
    }

    public static String translateFromMorseCode(final String morseCode) {
    String[] data = morseCode.split(" ");
    StringBuilder result = new StringBuilder();
    for(String s:data) result.append(english.get(s));
    return result.toString();
    }
    }
于 2015-11-20T13:29:44.617 回答