1

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

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

7 回答 7

2

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

输入

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

翻译逻辑

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

输出

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

建议

给你几个建议:

  1. 如果要处理输入中的空格字符,请将其添加到数组中!
  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. 要构建您的输出,我建议使用StringBuilder。因此,对于循环中的每次迭代,builder.append(...)当您准备好将其打印出来时,您可以使用builder.toString()

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

于 2015-04-17T18:50:04.040 回答
2

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

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

}
于 2017-06-30T10:12:43.423 回答
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); 
于 2015-04-17T18:39:13.603 回答
1

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

  1. 首先,您为英文字母数字创建了一个字符串数组。由于您从用户那里获取输入并将其拆分为 char,因此您应该创建一个 char 数组。由于您试图将用户输入与您的数组进行比较,因此您使用的是 some.equals(something else) --> 这是 String.. 的一种方法。现在您有两个要比较的字符,请使用==比较符号。
  2. 启动一个变量并在同一行(更少的代码行)上声明它的起始值是一种很好的做法。for 循环也是如此,直接在循环声明中启动索引变量。(通常以字母i而不是变量开头index)。
  3. 最后的双for loop精度对于比较输入中的每个字符与英文字母和数字的每个字符是必要的。
  4. 对于下面建议的答案,我使用 aString 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);
} 
于 2015-04-17T18:54:28.857 回答
0

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

于 2015-04-17T18:28:58.420 回答
0

您需要遍历用户输入的每个字符,然后遍历英文字符以查找用户输入字符所在的位置englishenglish一旦找到,使用来自in的相同索引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]);
         {
     }
}  

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

于 2015-04-17T18:34:58.417 回答
0

如果您正在使用双向翻译器(莫尔斯 <=> 英语)并且您更喜欢 Java Stream 方法,那么我认为最好保留英文字符数组String而不是char- 这是由于chars 在 Stream 中的映射有点困难(这个问题供参考)这将使 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));
    }

}
于 2021-01-24T13:22:48.317 回答