【发布时间】:2020-08-23 10:47:44
【问题描述】:
我正在尝试编写一个简单的摩尔斯电码解码器。它需要一个摩尔斯电码字符串并将其转换为英语。我正在努力解决一个问题,我的代码没有解码最后一个字符。我想我知道问题出在哪里,但我无法自己解决,所以希望你能帮助我。 例如,如果我正在尝试解码“-... . --. .. -. - .... . -. -..” 这是“Begin The End”,它会将其解码为“Begin the En ”。
public class Main {
public static void main(String[] args) {
String codeToDecode = "-... . --. .. -. - .... . . -. -.."; // any random Morse code
String decode = "";
int flag = 0;
codeToDecode=codeToDecode.replace(' ','/');
Map<String, String> vocabulary = new HashMap<>(); //This is my "vocabulary"
vocabulary.put(".-", "a");
// it goes on this way, i'll cut next letters to save space.
...
vocabulary.put("--..", "z");
if(codeToDecode.length()<3){
decode += vocabulary.get(codeToDecode);
}
if(codeToDecode=="...---..."){
decode="SOS";
}
for (int i = 0; i <codeToDecode.length(); i++) {
if (codeToDecode.charAt(i) == '/') { // Here must be the problem. '/' is the blank space. My code "decodes" parts from space to space, but in the end of the string there is no blank space so it ignores last letter. I tried using "||i==codeToDecode.length()" in if statement, but it didn't work.
decode += vocabulary.get(codeToDecode.substring(flag, i));
flag = i + 1;
} if(codeToDecode.charAt(i)=='/'&&codeToDecode.charAt(i+1)=='/'){
decode+=" ";
i+=2;
flag+=2;
}
}
decode=decode.toUpperCase();
System.out.println(decode);
}
}
我知道我的方法会出现很多问题(我确信有更好的方法来完成这项任务),但我正在尝试自己完成这项任务,而不查看现成的示例。我希望我的代码和我的解释一样清楚。提前谢谢你。
和平与爱!
【问题讨论】:
标签: java string loops if-statement hashmap