0

Before I begin, I am a novice programmer having only been doing this for about a day.

How do I get my program to continue reading my input after an input has been fulfilled? for the below code, which is for a morse code to english translator I am trying to make, when I input morse, for example .-, it gives me the correct output, A. But when I combine morse letters, example .--..., which should be AB, the else statement activates. What should I do?

import java.util.Scanner;

public class MorseTranslator {

public static void main(String[] args) {

     System.out.println("Please enter morse code you wish to translate.");
     Scanner sc =new Scanner(System.in);
     String morse = sc.next();



     if (morse.equals(" ")) {
         System.out.print(" ");
        }
     if (morse.equals(".-")){
         System.out.print("A");
        }
     if (morse.equals("-...")){
         System.out.print("B");
        }
     if (morse.equals("-.-.")){
         System.out.print("C");
        }
     if (morse.equals("-..")){
         System.out.print("D");
        }
     if (morse.equals(".")){
         System.out.print("E");
        }
     if (morse.equals("..-.")){
         System.out.print("F");
        }


     else System.out.println("Please input morse code.");

}

}

4

2 に答える 2

1

String.equals() は完全な文字列を比較するため、.--... が .- と等しくなることはありません。そのため、String.indexOf() を使用してモールス文字列内を「探す」必要があります。

 if(morse.indexOf(".-")!=-1){
    System.out.print("A");
    //need more magic here
 }

ここで、モールス文字列からこれらの 2 つの文字を「減算」または取り出し、ループで検索を繰り返す必要があります。

 if(morse.indexOf(".-")!=-1){
    System.out.print("A");
    morse=morse.substring(morse.indexOf(".-")+2); // where 2 morse characters
    continue; //your hypothetical loop
 }
 if(morse.indexOf("-...")!=-1){
    System.out.print("B");
    morse=morse.substring(morse.indexOf("-...")+4); // where 4 morse characters
    continue; //your hypothetical loop
 }
 ...

処理するデータがなくなるまでループすることを忘れないでください

于 2015-10-03T00:28:03.767 に答える