摩尔斯电码翻译(简单)

时间:2015-04-17 18:18:27

标签: java morse-code

我正在为我的编程入门课程编写一个简单的摩尔斯电码代码翻译器。这是一个非常简单的设计,基于我所教授的技术。

此程序适用于单个字符转换,但不能执行单词或句子。我认为问题与最后的morse[index]语句有关,但我无法弄清楚如何打印翻译的文本作为一个整体。

public class Exercise12_9
{
    public static void main(String[] args)
    {
        String[] english = { "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",
                  ",", ".", "?" };

        String[] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", 
                ".---", "-.-", ".-..", "--", "-.", "---", ".---.", "--.-", ".-.",
                "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
                "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
                "-----", "--..--", ".-.-.-", "..--.." };


        Scanner keyboard = new Scanner(System.in);

        String userInput;

        int index;

        index = 0;

        System.out.println(" This is an English to Morse Code Translator.  ");
        System.out.println(" Please enter what you would like translate ");
        System.out.println("             into Morse Code. ");
        System.out.println(" ============================================ ");

        userInput = keyboard.next();

        userInput = userInput.toLowerCase();

        for (index = 0; index < userInput.length(); index++)           
        {
            char [] chars = userInput.toCharArray();

            if (userInput.equals(english[index]))
            {    
                System.out.println(" Translated : " + morse[index]);       
            }
        }  
    }
}

7 个答案:

答案 0 :(得分:1)

我认为这可能是您的解决方案。

Scanner keyboard = new Scanner(System.in);
    String  userInput = keyboard.nextLine();

    String output;
    for (index = 0; index < userInput.length(); index++)           
      {
         if (Arrays.asList(english).contains(userInput[index]))
         {        
             output+=morse[index];
         }
      } 
    System.out.println(" Translated : " +  output); 

答案 1 :(得分:1)

你在这里有一些需要解决的问题,所以让我们来看看:

输入

Scanner.next()只会提供下一个令牌。在您的情况下,您需要整个字符串。请尝试使用Scanner.nextLine()

译者逻辑

当前代码存在的方式,你正在逐步完成输入(正确),但是对于输入中的每个字符,你都没有在摩尔斯电码中获取等价物!您只需将整个输入与english[index]处的单个英文字符进行比较。请参阅下文,了解修复逻辑的建议。

输出

另请注意,您在每个字符后打印出已翻译的字符串,我认为您不想这样做。

建议

为您提出一些建议:

  1. 如果要处理输入中的空格字符,请将其添加到数组中!
  2. 我强烈建议您将英语和莫尔斯字符存储在Map中。通过这种方式,您可以非常轻松地查找相当于英文字符的Morse。如果您愿意,您的阵列仍然可以,但是在初始化之后可能会添加以下内容:

    final Map<String, String> mapping = new HashMap<String, String>();
    for (int i = 0; i < english.length; ++i) {
        mapping.put(english[i], morse[i]);
    }
    

    现在,您可以使用mapping.get(String.valueOf(userInput.charAt(index)))在循环中查找莫尔斯字符。

  3. 要建立输出,我建议使用StringBuilder。因此,对于循环中的每次迭代builder.append(...),当您准备打印出来时,可以使用builder.toString()

  4. 这绝对是一个更适合代码审查的答案,但是嘿,它回答了你的逻辑问题。希望这有帮助!

答案 2 :(得分:0)

如果你查看Scanner.Next()的java文档,你会注意到next只返回下一个标记。使用Scanner.nextLine()来获取一行文本而不只是一个令牌。

答案 3 :(得分:0)

您需要遍历用户输入的每个字符,然后遍历英语字符以查找用户输入字符在english中的位置。找到后,使用englishmorse的相同索引。我假设englishmorse的长度相同,morse[0]是摩尔斯电码中english[0]的翻译。

userInput = userInput.toCharArray();
for (index = 0; index < userInput.length; index++) { 
     for (int i = 0; i < english.length; i++) {
         if (userInput[index] == english[i]) {
             System.out.println(" Translated : " + morse[i]);
         {
     }
}  

您还需要使用Scanner.nextLine()作为@WhiteNightFury建议的用户输入。

答案 4 :(得分:0)

我相信你正在努力实现这样的目标。你走的路很好,虽然你需要看看我的代码中的一些指示。

  1. 首先,您为英语字母数字创建了一个String数组。由于您从用户获取输入并将其拆分为char,因此您应该创建一个char数组。由于您尝试将用户输入与数组进行比较,因此您使用的是something.equals(其他内容) - &gt;这是String的一个方法..现在你有两个要比较的字符使用==比较符号。
  2. 优良作法是启动变量并在同一行(较少的代码行)上声明它的起始值。 for循环也是如此,直接在循环声明中启动索引变量。 (通常以字母i开头,而不是变量index)。
  3. 最后需要双for loop来比较输入中的每个字符与英文字母和数字的每个字符。
  4. 对于下面建议的答案,我使用String str来连接莫尔斯值。然后你只需打印出它的价值。
  5. 虽然我修改了一些你的代码,然后使用并查看它创建的不同输出,这是从给出的代码中学习的最佳方法。

    祝学习好运

    public static void main(String[] args){
    
        char[] english = { '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',
                      ',', '.', '?' };
    
        String[] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", 
                    ".---", "-.-", ".-..", "--", "-.", "---", ".---.", "--.-", ".-.",
                    "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
                    "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
                    "-----", "--..--", ".-.-.-", "..--.." };
    
        //Scanner keyboard = new Scanner(System.in);
    
        System.out.println(" This is an English to Morse Code Translator.  ");
        System.out.println(" Please enter what you would like translate ");
        System.out.println("             into Morse Code. ");
        System.out.println(" ============================================ ");
    
        //String userInput = keyboard.nextLine().toLowerCase();
        String userInput = "TEST".toLowerCase();
    
        char[] chars = userInput.toCharArray();
    
        String str = "";
        for (int i = 0; i < chars.length; i++){
            for (int j = 0; j < english.length; j++){
    
                if (english[j] == chars[i]){
                    str = str + morse[j] + " ";  
                }
            }
        }
        System.out.println(str);
    } 
    

答案 5 :(得分:0)

以下是您的解决方案的优化代码

public class MorseCode {
public static Scanner sc;
public static void main(String args[]) throws IOException  //Input Output Exception is added to cover the BufferedReader 
{
    int option = 0;
    String sentence = "",answer = "",answer1 = "";
     char[] english = { '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',
             ',', '.', '?' };   //Defining a Character Array of the English Letters numbers and Symbols so that we can compare and convert later 

     String[] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", 
                ".---", "-.-", ".-..", "--", "-.", "---", ".---.", "--.-", ".-.",
                "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
                "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
                "-----", "--..--", ".-.-.-", "..--.." };  //Defining an Array of String to hold the Morse Code value of Every English Letter,Number and Symbol in the same order as that of the character Array  
    sc = new Scanner(System.in);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println(">>>>Welcome to MorseCode Software<<<<");
    System.out.println("");
    do
    {
    System.out.println("-->Enter the Option Corresponding to the Task you want to Perform ");
    System.out.println("->1.Generate Morse Code<- OR ->2.Generate English Language<- OR ->3.Exit ");
    System.out.print("->");
    while(!sc.hasNextInt())  //Repeat Until the next Item is an Integer i.e Until the Next Item is an Integer Keep on Repeating it 
    {//NOTE- The hasnext() function is also used when we are using the Iterator where the next input is always checked and then if it is valid it is allowed to be entered 
        System.out.println("");
        System.err.println("-->ERROR<-->Enter Digits Only<--");
        System.out.print("->");
        sc.next();   //Repeat and Discard the previous Inputs which are not valid 
    }
    option = sc.nextInt();
    switch(option)
    {
    case 1:
    {
        System.out.println("");
        System.out.println("-->Enter the Sentence that you want to Transmit Using the Morse Code ");
        System.out.print("->");
        sentence = br.readLine();
        System.out.println("");
        sentence = sentence.toLowerCase(); //Because morse code is defined only for the lower case letters and the numbers and the Symbols will remain the Same
        char[] morsec = sentence.toCharArray();
        for(int i = 0; i < morsec.length;i++)  //The loop will run till i is less than the number of characters in the Sentence because Every Character needs to Be Converted into the Respective Morse Code 
        {//For Every Letter in the User Input Sentence
            for(int j = 0;j<english.length;j++)   //For Every Character in the morsec array we will have to traverse the entire English Array and find the match so that it can be represented 
            {
                if(english[j] == morsec[i])  //If the Character Present in English array is equal to the character present in the Morsec array then Only Execute 
                {//Always remember that the condition in the Inner loop will be the first to be Equated in the If Statement because that will change until the characters match 
                    answer = answer + morse[j] + " ";  //After Every Letter is generated in the Morse Code we will give a Space 
                }  //Since the Letters in the English char and the symbols present in the morse array are at the Same Index 
            }
        }
        System.out.println("-->The Morse Code Translation is:- ");
        System.out.print(">> ");
        System.out.println(answer);
        System.out.println("");
        break;
    }
    case 2:
    {
        System.out.println("");
        System.out.println("-->Enter the Morse Code and After Every Letter add Space in Between ");
        System.out.print("-> ");
        sentence = br.readLine();
        System.out.println("");
        String[] morsec = sentence.split(" ");   //To use the split function to Convert Every Morse Code String as a Separate Entry in the STring array 
        for(int i = 0;i < morsec.length;i++)
        {//For Every morse code Letter Entered 
        //Remember - We are Splitting on the Basis of the space     
            for(int j = 0;j < morse.length;j++)
            {
                if(morse[j].equals(morsec[i]))  //When you are comparing the String you have to Do this and not == 
                {
                    answer1 = answer1 + english[j];  //Since the characters in the Morse array and the English Array are in the Same Index
                }
            }
        }
        System.out.println("-->The English Language Translation is:- ");
        System.out.print(">> ");
        System.out.println(answer1);
        System.out.println("");
        break;
    }
    case 3:
    {
        System.out.println("");
        System.out.println(">>Thank you For Using this Service<<");
        System.out.println("");
        break;
    }
    default:
    {
        System.err.println("-->ERROR<-->Invalid Option Entered<--");
        System.out.println("");
        break;
    }
    }
    }
    while(option!=3);
    }

}

答案 6 :(得分:0)

如果您使用 双向 翻译器(Morse <=> 英语)并且您更喜欢 Java Stream 方法,那么我认为最好将英文字符数组保留为 String 而不是比 char - 这是由于流中 char 的映射稍微困难(this 问题供参考),这会使流方法更加混乱。

public class MorseCode {

    private static final String[] english = {
        "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",
        ",", ".", "?", "!", ":", "@", "=", "-", "+", "\"", "/", "&",
        "'", "(", ")"
    };

    private static final String[] morse = {
        ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
        ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
        "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
        "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
        "-----", "--..--", ".-.-.-", "..--..", "-.-.--", "---...", ".--.-.",
        "-...-", "-....-", ".-.-.", ".-..-.", "-..-.", ".-...", ".----.",
        "-.--.", "-.--.-"
    };

    private static final Map<String, String> EN_TO_MORSE = new HashMap<>();
    private static final Map<String, String> MORSE_TO_EN = new HashMap<>();

    static {
        for (int i = 0; i < english.length; i++) {
            EN_TO_MORSE.put(english[i], morse[i]);
            MORSE_TO_EN.put(morse[i], english[i]);
        }
    }

    public static void main(String[] args) {

        String output;

        output = MorseCode.run(false, "Hello, World!");
        System.out.println(output); // .... . .-.. .-.. --- --..-- / .-- --- .-. .-.. -.. -.-.--

        output = MorseCode.run(true, ".... . .-.. .-.. --- --..-- / .-- --- .-. .-.. -.. -.-.--");
        System.out.println(output); // hello, world!
    }

    private static String run(boolean codeToEnglish, String input) {

        if (input == null || input.length() == 0)
            throw new IllegalArgumentException("Invalid input");

        String wordSplitter, wordJoiner, charSplitter, charJoiner;
        Map<String, String> mapper;
        
        if (codeToEnglish) {
            wordSplitter = " / ";
            wordJoiner = " ";
            charJoiner = "";
            charSplitter = " ";
            mapper = MORSE_TO_EN;
        } else {
            wordSplitter = " ";
            wordJoiner = " / ";
            charJoiner = " ";
            charSplitter = "";
            mapper = EN_TO_MORSE;
        }

        return Arrays
            .stream(input.trim().toLowerCase().split(wordSplitter))
            .map(word -> createWord(word, charJoiner, charSplitter, mapper))
            .collect(Collectors.joining(wordJoiner));
    }

    private static String createWord(String word, String joiner, String splitter, Map<String, String> mapper) {
        return Arrays.stream(word.split(splitter)).map(mapper::get).collect(Collectors.joining(joiner));
    }

}
相关问题