dimanche 23 août 2020

Morse Code decoder problem with looping through String

I'm trying to write a simple Morse Code Decoder. It takes a Morse Code string and converts it into the English. I'm struggling with one problem, my code does not decode the last character. I guess I know where the problem is, but I can't resolve it on my own, so I hope you could help me. For example if I'm trying to decode "-... . --. .. -. - .... . . -. -.." which is "Begin The End" it decodes it to "Begin the En".

public class Main {

public static void main(String[] args) {

    String codeToDecode = "-... . --. .. -.  - .... .  . -. -.."; //  any random Morse code
    String decode = ""; 
    int flag = 0;
    codeToDecode=codeToDecode.replace(' ','/'); 
    Map<String, String> vocabulary = new HashMap<>(); //This is my "vocabulary" 
  
    vocabulary.put(".-", "a");
    // it goes on this way, i'll cut next letters to save space. 
    ...
    vocabulary.put("--..", "z");

     if(codeToDecode.length()<3){
        decode += vocabulary.get(codeToDecode);
    }
    
     if(codeToDecode=="...---..."){
        decode="SOS";
    }
    
   for (int i = 0; i <codeToDecode.length(); i++) {

        if (codeToDecode.charAt(i) == '/') { // Here must be the problem. '/' is the blank space. My code "decodes" parts from space to space, but in the end of the string there is no blank space so it ignores last letter. I tried using "||i==codeToDecode.length()" in if statement, but it didn't work.
            decode += vocabulary.get(codeToDecode.substring(flag, i));
            flag = i + 1;


        } if(codeToDecode.charAt(i)=='/'&&codeToDecode.charAt(i+1)=='/'){
                decode+=" ";
              i+=2;
                flag+=2;
      }
   }
        decode=decode.toUpperCase();
    System.out.println(decode);

 }
}
    
  

I understand there are many problems to come with my approach( I'm sure there is a better way to complete this task) but I'm trying to finish this one on my own without looking at the ready examples. I hope my code is clear as well as my explanations. Thank you in advance.

Peace and Love!

Aucun commentaire:

Enregistrer un commentaire