I looked for other examples on StackOverflow that might answer my question, but none of the answers in the other questions focused on a nested for loop. I'm making a Morse code translator, and the program itself works fine if I do this:
public static void StringtoMorse(String str){
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 [] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "|"};
for (int i = 0; i < str.length(); i ++){
for (int j = 0; j < Alphabet.length; j ++){
if (str.charAt(i) == Alphabet[j]){
System.out.print(MorseCode[j] + " ");
}
}
}
}
But I want to make the method so that it returns the String of (MorseCode[j] + " "). So this is how I edited my method to do that:
public static String StringtoMorse(String str){
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 [] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "|"};
for (int i = 0; i < str.length(); i ++){
for (int j = 0; j < Alphabet.length; j ++){
if (str.charAt(i) == Alphabet[j]){
return(MorseCode[j] + " ");
}
}
}
}
But that results in a compile error. The error says "This method must return a result of type String", but I thought the (MorseCode[j] + " ") is a string type. I know that MorseCode[j] has to be a String because I've defined MorseCode as a String array.
If I use the first method (With the System.out.println() method), it properly returns the result.