2017-11-20 10 views
1

私はモールス・コードに問題があります。ユーザーが単なるモールス・コード以上のものを入力したときには、単一の疑問符を印刷したいと思っています。である必要があり、現在、私はそれだけで次の行にスキップ持って、モールス・コードをモールスに翻訳する

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

モールス符号列から文字に変換するために 'Map'を使用してください。 "?" map.get(morseCodeString)がnullを返すとき。 – DwB

答えて

2

は、任意のループの外側上部に正規表現パターンを作る「?」:その後、

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日間で第2の同様な質問です...

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 
     } 

    } 

Q:どのようにあなたは特別に対処する予定ですかモーリス(例:...---) またはそれは割り当てられていませんか?

+0

ありがとうございます! 私はこれらのメソッドをまだ知りませんが、elseまたはループの場合にのみ使用できますか? – Koagon

+0

答えでUPDを見て... – Vadim

+0

私は "?"その場合も、あなたが作ったコードをテストしました。それは素晴らしいことです! どのようにあなたの現在のレベルに達しましたか?私はあなたのレベルのコーダーになることを切望しています – Koagon

関連する問題