摩尔斯电码翻译器(简单)

Morse code translator(simple)

我正在为我的编程入门开发一个简单的摩尔斯电码翻译器 class。这是一个基于我所学技术的非常简单的设计。

本程序适用于单个字符的转换,但不能转换单词或句子。我相信问题与末尾的 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]);       
            }
        }  
    }
}

如果您在 Scanner.Next() 查看 java 文档,您会注意到 next 只有 returns 下一个标记。使用 Scanner.nextLine() 获取一行文本而不是单个标记。

您需要遍历用户输入的每个字符,然后遍历英文字符以找到用户输入字符在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]);
         {
     }
}  

您还需要按照@WhiteNightFury 的建议使用Scanner.nextLine() 进行用户输入。

我认为这可以成为您的解决方案。

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

这里有几件事需要解决,让我们看一下:

输入

Scanner.next() 只会给出下一个标记。在您的情况下,您需要整个字符串。请尝试使用 Scanner.nextLine()

翻译逻辑

按照您的代码当前存在的方式,您正在单步执行输入(正确),但是对于输入中的每个字符,您并没有获取摩尔斯电码中的等效字符!您而是将 整个 输入与 english[index] 处的单个英文字符进行比较。请参阅下面的建议来修复您的逻辑。

输出

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

建议

给您的几条建议:

  1. 如果您想处理输入中的 space 个字符,请将其添加到您的数组中!
  2. 我强烈建议将您的英语和莫尔斯字符存储在 Map 中。这样,您就可以非常轻松地查找等同于英语字符的摩尔斯电码。如果您愿意,您的数组仍然可以,但也许在初始化后添加以下内容:

    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. 在循环中查找摩尔斯字符
  4. 要建立输出,我建议使用 StringBuilder。因此,对于循环中的每次迭代,builder.append(...),当您准备好将其打印出来时,您可以使用 builder.toString()

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

我相信你正在努力实现这样的目标。尽管您需要看一下我为您的代码提供的一些提示,但您走的路很好。

  1. 首先,您为英文字母数字创建了一个字符串数组。由于您从用户那里获取输入并将其拆分为 char,因此您应该创建一个 char 数组。由于您试图将用户输入与您的数组进行比较,因此您使用的是 something.equals(其他) --> 这是 String 的一种方法。现在您有两个要比较的字符,请使用 ==比较符号.
  2. 在同一行(更少的代码行)启动一个变量并声明它的起始值是一种很好的做法。 for 循环也是如此,直接在循环声明中初始化索引变量。 (通常以字母 i 而非变量 index 开头)。
  3. 末尾的双for loop是比较输入的每个字符和你的英文字母和数字的每个字符所必需的。
  4. 对于下面建议的答案,我使用了 String str 来连接莫尔斯值。然后你只需要打印出它的价值。

尽管我对您的代码做了一些修改,试用并查看了它创建的不同输出,但这是从给定代码中学习的最佳方式。

祝学习顺利

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

这是您给定解决方案的优化代码

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

}

如果您追求 two-way 翻译器(莫尔斯 <=> 英语)并且您更喜欢 Java 流方法,那么我认为最好保留英语字符数组为 String 而不是 char - 这是由于 chars 在 Stream 中的映射稍微困难(this 问题供参考)这将使 Stream 方法成为有点混乱。

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

}