I know this kind of question is common throughout StackOverFlow, but the question I have is much more specific. In my program, I have the main() method, an English to Morse method that works fine, and a Morse to English method that I am having trouble with.
public static void MorsetoString(String Morse, char [] Alphabet, String [] MorseCode){
StringBuffer English = new StringBuffer();
for(int i=0;i < Morse.length(); i++){
if (Morse.charAt(i) != ' '){
for (int j = 0; j < MorseCode.length; j ++){
if (Morse.charAt(i) == MorseCode[j]){
English.append(MorseCode[j]);
English.append(" ");
}
}
}
}
}
These are the arrays that are taken as arguments in this method:
char Alphabet [] = {'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', ' '};
String MorseCode [] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "..-", ".--", "-..-", "-.--", "--..", "|"};
The code is not completely done as I have to add the statement for when Morse.charAt(i) == ' '
, but I'm mainly having trouble with this portion.
The problem with this code is that when I say if (Morse.charAt(i) == MorseCode[j])
, I am comparing a char type variable to a string type, so the program does not compile. I think my code works overall in terms of logic, but is there any way I can modify the code so that the two can be compared? The exact error message is "
You don't need to compare every character of input string. Compare just when you get space ' '
, because space divides characters in Morse code:
static char alphabet[] = {'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', ' '};
static String morseCode[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "..-", ".--", "-..-", "-.--", "--..", "|"};
public static void decodeMorse(String morse){
StringBuilder english = new StringBuilder();
int codeLength = 0;
for(int i=0; i<morse.length();i++){
String code = null;
// if we met ' ', we can get previous code
if(morse.charAt(i)==' ' && codeLength>0){
code = morse.substring(i-codeLength, i);
codeLength=0;
}else
// when we reached end of string we have to get previous code
if(i==morse.length()-1 && codeLength>0){
code = morse.substring(i-codeLength, morse.length());
}
else{
codeLength++;
}
// if you got the code, find alphabet char for it
if(code!=null){
for(int j=0; j<alphabet.length; j++){
if(code.equals(morseCode[j])){
english.append(alphabet[j]);
}
}
}
}
System.out.println(english);
}
Also, you don't need add spaces between alphabet chars, because in English are not needed spaces between letters.