gpt4 book ai didi

java - 摩尔斯电码转英语 : Character type is not Comparable with String type

转载 作者:行者123 更新时间:2023-12-01 10:19:43 26 4
gpt4 key购买 nike

我知道这种问题在 StackOverFlow 中很常见,但我的问题要具体得多。在我的程序中,我有 main() 方法,一个工作正常的英语到莫尔斯电码方法,以及一个我遇到问题的莫尔斯电码到英语方法。

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(" ");
}
}
}

}



}

这些是在此方法中用作参数的数组:

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 [] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "..-", ".--", "-..-", "-.--", "--..", "|"};

代码尚未完全完成,因为我必须添加 while Morse.charAt(i) == ' ' 的语句,但我主要在这部分遇到问题。

这段代码的问题是,当我说 if (Morse.charAt(i) == MorseCode[j]) 时,我正在将 char 类型变量与字符串类型进行比较,因此程序无法编译。我认为我的代码在逻辑上总体上是有效的,但是有什么方法可以修改代码以便将两者进行比较吗?确切的错误消息是“

最佳答案

您不需要比较输入字符串的每个字符。当你得到空格' '时进行比较,因为空格在摩尔斯电码中划分字符:

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);
}

此外,您不需要在字母字符之间添加空格,因为在英语中,字母之间不需要空格。

关于java - 摩尔斯电码转英语 : Character type is not Comparable with String type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35678615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com