【问题标题】:Morse code translating morse into language java莫尔斯电码将莫尔斯码翻译成java语言
【发布时间】:2017-11-20 19:51:18
【问题描述】:

我的莫尔斯电码有点问题,特别是当用户输入的不仅仅是莫尔斯电码(即 .-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

【问题讨论】:

  • 使用Map 将莫尔斯电码字符串转换为字母。打印“?”当 map.get(morseCodeString) 返回 null 时。

标签: java morse-code


【解决方案1】:

在任何循环之外的顶部制作 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
        }

    }

问:你打算如何处理特殊的莫尔斯(例如......) 还是不在分配中?

【讨论】:

  • 谢谢!虽然我还不知道这些方法,但你能不能只用 if else 或 loops 来做呢?
  • 我打算打印一个“?”在这种情况下,我也测试了您编写的代码,它运行良好!你是如何达到现在的水平的?我渴望成为您级别的程序员
  • 谢谢。别担心……20年后你会比我好得多。 :-) 祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
  • 2021-11-24
相关资源
最近更新 更多