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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29706653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:46:34  来源:igfitidea点击:

Morse code translator(simple)

javamorse-code

提问by Derek Boeka

I am working on a simple Morse Code translator for my Intro to Programming class. This is a very simple design based on the techniques I have been taught.

我正在为我的 Intro to Programming 课程开发一个简单的莫尔斯电码翻译器。这是一个非常简单的设计,基于我所学的技术。

This program works for a single character conversion, but cannot do words or sentences. I believe the problem has to do with the morse[index]statement at the end, but I can't figure out how to print the translated text as a whole.

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

采纳答案by qcGold

I believe you are trying to achieve something like this. You were on a good path, although you need to take a look at a few pointers I have for your code.

我相信你正在努力实现这样的目标。您走在一条不错的道路上,尽管您需要查看我为您的代码提供的一些指示。

  1. first of all you created an array of String for the alphanumeric in english. Since you take an input from user and split it in char, you should have created an array of char instead. Since you were trying to compare user input with your array, you were using something.equals(something else) --> this is a method for String.. Now that you have two character to compare use the ==comparision sign.
  2. It is good practice to initiate a variable and declare it's starting value on the same line (less line of code). Same thing goes for the for loop, initiate the index variable directly in the loop declaration. (Usually starting with letter iinstead of the variable index).
  3. The double for loopat the end is necessary to compare every character from the input to every character of your english letters and numbers.
  4. For the answer suggested below, I used a String strto concatenate the morse value. Then you simply have to print out it's value.
  1. 首先,您为英文字母数字创建了一个字符串数组。由于您从用户那里获取输入并将其拆分为字符,因此您应该创建一个字符数组。由于您试图将用户输入与您的数组进行比较,因此您使用了 something.equals(something else) --> 这是 String 的一种方法。现在您有两个字符可以使用==比较符号进行比较。
  2. 启动一个变量并在同一行(更少的代码行)上声明它的起始值是一种很好的做法。for 循环也是如此,直接在循环声明中启动索引变量。(通常以字母i而不是变量开头index)。
  3. for loop为了将输入中的每个字符与英文字母和数字的每个字符进行比较,最后的 double是必要的。
  4. 对于下面建议的答案,我使用 aString str来连接莫尔斯值。然后你只需要打印出它的价值。

Although I modified a bit your code, play around with with and see the different outputs it creates, this is the best way to learn from the code given.

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

Good luck with the learning

祝学习顺利

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

回答by Radhesh Khanna

Here is the Optimized Code of your Given Solution

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

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

}

回答by Diptopol Dam

I think this can be your solution.

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

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

回答by avojak

You've got a couple things here that need to be addressed, so lets take a look:

这里有几件事需要解决,所以让我们来看看:

Input

输入

Scanner.next()is only going to give only the next token. In your case, you want the entire string. Try using Scanner.nextLine()instead.

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

Translator Logic

翻译逻辑

The way your code exists currently, you are stepping through the input (correct), but for each character in the input, you're not fetching the equivalent in Morse Code! You're instead comparing the entireinput to the single English character at english[index]. See below for a suggestion to fix your logic.

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

Output

输出

Also notice that you are printing out a translated String after eachcharacter, which I don't think you want to do.

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

Suggestions

建议

Couple of suggestions for you:

给你几个建议:

  1. If you want to handle a space character in the input, add that to your arrays!
  2. I would highly suggest storing your English and Morse characters in a Map. This way, you can very easily look up the Morse equivalent to an English character. Your arrays are ok still if you would like, but perhaps add the following after they're initialized:

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

    Now with this, you can look up the Morse character in your loop using mapping.get(String.valueOf(userInput.charAt(index))).

  3. To build up your output, I would recommend using StringBuilder. So for each iteration in your loop, builder.append(...), and when you're ready to print it out, you can use builder.toString()

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

This was definitely an answer better-suited for a code review, but hey, it answered your logic issue. Hope this helps!

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

回答by Gelunox

if you look in the java documentation at Scanner.Next()you'll notice that nextonly returns the next token. use Scanner.nextLine()to get a line of text instead of just a single token.

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

回答by Code Whisperer

You need to loop through every char of the user input and then loop through the English chars to find where the user input char is located in english. Once found use the same index from englishin morse. I am assuming englishand morsehave same length and morse[0]is the translation of english[0]in morse code.

您需要遍历用户输入的每个字符,然后遍历英文字符以查找用户输入字符在english. 一旦找到,就使用englishin 中的相同索引morse。我假设english并且morse具有相同的长度并且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]);
         {
     }
}  

You also need to use Scanner.nextLine()for user input as @WhiteNightFury suggested.

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