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

时间:2017-11-20 19:51:19

标签: java morse-code

我的摩尔斯电码有点问题,特别是当用户输入的不只是莫尔斯电码时,我希望它打印出一个问号,即。-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

1 个答案:

答案 0 :(得分:2)

使RegEx模式位于任何循环之外的顶部:

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

然后在内部循环而不是

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

你的if是:

        if(regExPattern.matcher(words[i]).matches()) {
           //it is MORSE code - translate it
           ...
        } else {
           // it is something else 
           System.out.print("?")
         }
BTW:有更好的解决方案,而不是使用数组。检查我的答案中的代码: 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
        }

    }
问:你打算怎么处理特殊的MORSE(例如......---)    或者它不是在分配?