【发布时间】:2016-06-06 21:47:02
【问题描述】:
我在 StackOverflow 上寻找可能回答我的问题的其他示例,但其他问题中的答案都没有集中在嵌套的 for 循环上。我正在制作一个摩尔斯电码翻译器,如果我这样做,程序本身就可以正常工作:
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] + " ");
}
}
}
}
但我想创建该方法,以便它返回 (MorseCode[j] + " ") 的字符串。所以这就是我编辑我的方法来做到这一点的方式:
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] + " ");
}
}
}
}
但这会导致编译错误。错误说“此方法必须返回字符串类型的结果”,但我认为 (MorseCode[j] + " ") 是字符串类型。 我知道 MorseCode[j] 必须是字符串,因为我已将 MorseCode 定义为字符串数组。
如果我使用第一种方法(使用 System.out.println() 方法),它会正确返回结果。
【问题讨论】: