Search code examples
javaarraysstringequalsmorse-code

String.equals-method always returns false while comparing two Strings


My task for university my was to code a Morse-Code-Decoder. I have String-Array with every letter of the "morse-alphabet" in it. In a for-loop I cut the sentence in morsecode into it's "morseletters" using the substring-method. I've made another for-loop and and an if-statement, to check which letter from the "morse-alphabet" matches the current "morseletter". I've used the String.equals-method, but it does'nt work. Even if the two Strings are the same. I also printed the length of every String in the loop, to check if the Strings contained some unwanted spaces. But even though the Strings looked the same and had the same length, the condtion of my if-statement would never be true. The problem appers to be the equals-method. What do I have to change, so that my code works?

public class Morse {
private static String[] morsecodes = { ".-", "-...", "-.-.", "-..", ".",
         "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.",
         "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--",
         "-..-", "-.--", "--.." }; 

public static void  main (String args[]) {
    System.out.println(decodeMorseCode(".... . .-.. .-.. --- .-- --- .-. .-.. -.."));       
}
public static String decodeMorseCode(String morseText) {
    String realText = "";
    String morseLetter = "";
    int counter = 0;

    for(int i = 0; i < morseText.length(); i++) {   
        if((morseText.charAt(i)==' ')) {
            morseLetter = morseText.substring(counter,i);
            counter = i+1;
        }
        if(morseText.charAt(i)==' '||i+1==morseText.length()) {
            for (int j = 0; j < 26; j++) {
                if((morsecodes[j].equals(morseLetter))) { //this is the if-statemen which causes the problem
                    char c = (char)(j+97);
                    realText += c;
                }

                if(j+1<=morseText.length()) {
                    if(morseText.charAt(j)==' '&& morseText.charAt(j+1)==' ') {
                        realText += " ";
                    }
                }

            morseLetter = "";
            }
        }           
    }
    return realText;
}

}


Solution

  • Remove the line morseLetter = ""; as shown below, and your code will work.

        if(morseText.charAt(i)==' '||i+1==morseText.length()) {
            for (int j = 0; j < 26; j++) {
                if(morsecodes[j].equals(morseLetter)) { //this is the if-statemen which causes the problem
                    char c = (char)(j+97);
                    realText += c;
                }
    
                if(j+1<=morseText.length()) {
                    if(morseText.charAt(j)==' '&& morseText.charAt(j+1)==' ') {
                        realText += " ";
                    }
                }
                //morseLetter = "";
            }
        }