Java 摩尔斯电码转换器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20914165/
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-08-13 05:17:12  来源:igfitidea点击:

Morse Code Converter

javaarraysstringindexingconverter

提问by LongGone

I already posted a topic on this but have considerably (and that topic was put on hold..so I can't edit) changed my code (I tried what one of the users said in different variations, but no beans). I've tried running just toMorse, but although it compiles I get no output and an error message of 'java.lang.ArrayIndexOutOfBoundsException(at projmorsejava:22 and 46)'I'm not sure how to configure toEnglish, at this point I've tried using the replaceAll, indexOf and valueOf methods. I've also tried using plaintextString but that also did not work out (I may have implemented it incorrectly). Here is my revised code:

我已经就此发布了一个主题,但已经相当多地(该主题被搁置......所以我无法编辑)更改了我的代码(我尝试了其中一位用户所说的不同变体,但没有豆类)。我试过只运行 toMorse,但是虽然它编译了,但我没有得到任何输出,而且'java.lang.ArrayIndexOutOfBoundsException(at projmorsejava:22 and 46)'我不知道如何配置toEnglish 的错误消息,此时我已经尝试使用 replaceAll、indexOf 和 valueOf 方法。我也尝试过使用 plaintextString 但这也没有奏效(我可能没有正确地实现它)。这是我修改后的代码:

import java.util.Scanner;

public class ProjMorse
{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String[] alpha = { "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[] dottie = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
                "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
                "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
                "-.--", "--..", ".----", "..---", "...--", "....-", ".....",
                "-....", "--...", "---..", "----.", "-----", "|" };

        System.out
                .println("Enter English to convert from English or Morse to convert from Morse:");

        String ans = input.nextLine();

        if (ans.equals("English")) {
            System.out.println("Please enter the text you would like   to convert to Morse Code: ");
            String english = input.nextLine();

            char[] translates = (english.toLowerCase()).toCharArray();
            System.out.println(toMorse(translates, dottie)); //calls on method toMorse

                }
                        else if (ans.equals("Morse")) {
            System.out
                    .println("Please enter the text you would like to convert to English (separate words with '|'):");
            String code = input.nextLine();

             String[] translates = (code.split("[|]", 0));
                     System.out.println(toEnglish(translates, alpha));//calls on method toEnglish

        }
    else
    System.out.println("Invalid input, please try again.");
     }

       public static String toMorse(char [] translates, String [] dottie)
       {            
      String morse = "";
      for (int j = 0; j < translates.length; j++)
      {
        char a = translates[j];
        if(Character.isLetter(a))
        {
           morse = dottie[a + 'a'];
        }
      }
      return morse;/*so I tried running only this(commented other stuff out) and it compiled but although it ran it didnt translate */
    }

    public static String toEnglish(String [] translates, String  [] alpha)
    {
      String s;
      for (int n = 0; n < translates.length; n++)
      {
        String a = translates[n];
                s = java.util.Arrays.asList(alpha).(Character.toChars(a + 'a')[0]);//I'm not sure what to do here..
      }
      return s;
    }
}

采纳答案by ShinTakezou

There are several things that do not work:

有几件事不起作用:

  1. missing initial public class ...(I suspect a copy-paste error)
  2. missing import java.util.Scanner;since you use Scanner
  3. wrong call to toMorse: first, two args are expected (check the method signature); then, first argument's name is not morse(unknown symbol), it must be translates, which you have just "created"! About the second: you need the array of strings that has in place of the e.g. "e" the morse code, so second argument must be... dottie
  4. wrong call to toEnglish: two args required (check the method signature, as done before!); the first, has to be translates, again (unknown s, as morsebefore)! About second argument: see above but of course since you have morse in input, you need the other array.
  5. in toMorseyou pick each char using translates[j], not valueOf.
  6. similarly, in toEnglishyou get the string using translates[n]
  7. in both toEnglishand toMorse, you have to "accumulate" the converted string into a string, and return it at the end, i.e. outside the loops!
  8. having a string, you pick the char at pos 0 using .charAt(0): to perform an op like x - 'a'x can't be a string, so since you have a string, you must get its first char.
  9. Note: about your using of morseand s: variable names in a method has nothing to do with variable names in the caller!
  1. 缺少首字母public class ...(我怀疑是复制粘贴错误)
  2. 缺少,import java.util.Scanner;因为您使用扫描仪
  3. 错误调用toMorse:首先,需要两个参数(检查方法签名);然后,第一个参数的名称不是morse(未知符号),它必须是translates您刚刚“创建”的名称!关于第二个:您需要代替摩尔斯电码“e”的字符串数组,因此第二个参数必须是... dottie
  4. 错误调用toEnglish:需要两个 args(检查方法签名,如前所述!);第一个,必须是translates,再次(未知s,和morse以前一样)!关于第二个参数:见上文,但当然,因为输入中有莫尔斯,你需要另一个数组。
  5. toMorse您选择每个字符时使用translates[j],而不是valueOf.
  6. 同样,在toEnglish你使用translates[n]
  7. toEnglishand 中toMorse,您必须将转换后的字符串“累积”为字符串,并在最后返回,即在循环之外!
  8. 有一个字符串,你使用.charAt(0):在 pos 0 处选择字符来执行像x - 'a'x这样的操作不能是一个字符串,所以因为你有一个字符串,你必须得到它的第一个字符。
  9. 注意:关于您在方法中使用morses:变量名与调用者中的变量名无关!

Example for toMorse:

示例toMorse

    String morse = "";
    for (int j = 0; j < translates.length; j++)
    {
        char a = translates[j];
        if(Character.isLetter(a))
        {
            morse += dottie[a - 'a'];
        }
    }
    return morse;  // this symbol is unknown to the caller

You will call it with something as simple as

你会用一些简单的东西来调用它

              System.out.println(toMorse(translates, dottie));

The fix for toEnglishis very similar (though your original code won't work), I hope you can do it by yourself.

的修复toEnglish非常相似(尽管您的原始代码不起作用),我希望您可以自己完成。

I think is all, more or less.

我认为是全部,或多或少。

Suggestion to fix toEnglish:

建议改成英文:

For each string you have in your translatesarray, you have to search into dottiestring array in order to search for that particular sequence of dots and lines.

对于translates数组中的每个字符串,您必须搜索dottie字符串数组以搜索特定的点和线序列。

If you find it, the position (index) you find it at, it's also the index of the right letter you keep in the alphaarray. So you might need to add that array as argument and use the index to pick the letter.

如果你找到它,你找到它的位置(索引),它也是你保留在alpha数组中的正确字母的索引。因此,您可能需要将该数组添加为参数并使用索引来选择字母。

Or, rather, you can use the same "trick" you used to toMorseand keep the toEnglishmethod signature unchanged: once you have the index, since you have found it, you can "invert" the coding algorithm, so you have to add 'a'to that index (integer) to obtain the code for the letter.

或者说,你可以用你用同样的“猫腻” toMorse,并保持toEnglish方法签名不变:一旦你的指标,既然你找到了,你可以“反转”的编码算法,所以你要添加'a'到索引(整数)以获取字母的代码。

You can use something like Character.toChars(k + 'a')[0]to take the char you want to add to the "accumulation string", being kthe index.

您可以使用类似的Character.toChars(k + 'a')[0]方法将要添加到“累积字符串”的字符作为k索引。

The cumbersome notation Character.toChars(k + 'a')[0]is since indeed Character.toCharsreturns an array, so we pick the first element of that array, which is the char we need.

麻烦的符号Character.toChars(k + 'a')[0]是因为确实Character.toChars返回一个数组,所以我们选择该数组的第一个元素,这是我们需要的字符。

回答by ug_

Its important you work out these errors by yourself to learn the necessary debugging skills that programming requires. This probably isnt what you are looking for but:

您自己解决这些错误以学习编程所需的必要调试技能很重要。这可能不是您要找的,但是:

  1. Always start at the first error and work your way down the list.
  2. When you encounter an error message and you dont know what the heck is going wrong take a look at some code samples. Look up "java how to (enter what your trying to do here)"the is a ton of information out there. When choosing what to search make sure you break it down to its most basic form, such as "java how to convert integer to string"
  3. Use a IDE, it may take a bit to get used to but it will be well worth the investment. Theres a very simple looking one called http://www.jedit.org/it would be right up your alley
  1. 始终从第一个错误开始,然后按照自己的方式在列表中工作。
  2. 当您遇到错误消息并且您不知道到底出了什么问题时,请查看一些代码示例。查找"java how to (enter what your trying to do here)"那里有大量信息。在选择要搜索的内容时,请确保将其分解为最基本的形式,例如"java how to convert integer to string"
  3. 使用 IDE,可能需要一点时间来习惯,但它非常值得投资。有一个非常简单的叫http://www.jedit.org/它会在你的胡同里