摩尔斯电码将摩尔斯语翻译成语言 java

Morse code translating morse into language java

我的摩尔斯电码有点问题,特别是我希望它在用户输入的不仅仅是摩尔斯电码时打印出一个问号,即 .-asd,输出应该是“?” ,目前我只是跳到下一行,

import java.util.Scanner;

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

     Scanner input = new Scanner(System.in);

     String line;
     while(!(line = input.nextLine().toUpperCase()).equals("*")){
         String[] words = line.split(" ");
         String output = "";

         for(int i = 0; i< words.length; ++i){
             if(words[i].length() == 0){
                 output += " ";
                 continue;
             }
             if(words[i].charAt(0) == '-' || words[i].charAt(0) == '.'){ //if it begins as morse code
                 for (int d = 0; d < MORSE.length; ++d) {
                     if(words[i].equals(MORSE[d]))
                         output += (char)('A'+d);
                 } //i wanted here to make a condition where if it starts as morse and follows with other things other than morse print out a single "?".
             } else System.out.print("?") //prints ("?") if its not morse code

在任何循环之外的顶部制作 RegEx 模式:

java.util.regex.Pattern regExPattern= java.util.regex.Pattern.compile("([\.,\-]){1,}");

然后在内部循环而不是

   if(words[i].charAt(0) == '-' || words[i].charAt(0) == '.')

你的条件是:

        if(regExPattern.matcher(words[i]).matches()) {
           //it is MORSE code - translate it
           ...
        } else {
           // it is something else 
           System.out.print("?")
         }

顺便说一句:有比使用数组更好的解决方案。检查我的答案中的代码: Morse Code Translator

只是想知道那个作业是从哪里来的:-)? 这是最近3天内的第二个类似问题...

UPD:仅用于循环(它还消除了非莫尔斯.-序列)

for (int i = 0; i < words.length; ++i) {
        boolean gotMorse = false;
        for (int d = 0; d < MORSE.length; d++) {
            if (MORSE[d].equals(words[i])) {
                // code found.
                output += (char) ('A' + d);
                gotMorse = true;
                break;
            }
        }
        if (!gotMorse) {
            output += "?";
            // or System.out.print("?"); if you do not need ? in the output
        }

    }

问:你打算如何处理特殊的莫尔斯电码(例如...---) 或者它不在作业中?