莫尔斯电码解码问题,循环遍历字符串部分。

huangapple go评论75阅读模式
英文:

Morse Code decoder problem with looping through String

问题

public class Main {

    public static void main(String[] args) {

        String codeToDecode = "-... . --. .. -.  - .... .  . -. -.."; // 任意随机的莫尔斯码
        String decode = "";
        int flag = 0;
        codeToDecode = codeToDecode.replace(" ", "/"); 
        Map<String, String> vocabulary = new HashMap<>(); // 这是我的“词汇表”
      
        vocabulary.put(".-", "a");
        // 这里继续添加其他映射
        
        vocabulary.put("--..", "z");

        if (codeToDecode.length() < 3) {
            decode += vocabulary.get(codeToDecode);
        }
        
        if (codeToDecode.equals("...---...")) {
            decode = "SOS";
        }
        
        for (int i = 0; i < codeToDecode.length(); i++) {

            if (codeToDecode.charAt(i) == '/') {
                decode += vocabulary.get(codeToDecode.substring(flag, i));
                flag = i + 1;
            }
            
            if (i + 1 < codeToDecode.length() && codeToDecode.charAt(i) == '/' && codeToDecode.charAt(i + 1) == '/') {
                decode += " ";
                i += 2;
                flag += 2;
            }
        }
        
        decode = decode.toUpperCase();
        System.out.println(decode);
    }
}
英文:

I'm trying to write a simple Morse Code Decoder. It takes a Morse Code string and converts it into the English. I'm struggling with one problem, my code does not decode the last character. I guess I know where the problem is, but I can't resolve it on my own, so I hope you could help me.
For example if I'm trying to decode "-... . --. .. -. - .... . . -. -.." which is "Begin The End" it decodes it to "Begin the En".

public class Main {
public static void main(String[] args) {
String codeToDecode = &quot;-... . --. .. -.  - .... .  . -. -..&quot;; //  any random Morse code
String decode = &quot;&quot;; 
int flag = 0;
codeToDecode=codeToDecode.replace(&#39; &#39;,&#39;/&#39;); 
Map&lt;String, String&gt; vocabulary = new HashMap&lt;&gt;(); //This is my &quot;vocabulary&quot; 
vocabulary.put(&quot;.-&quot;, &quot;a&quot;);
// it goes on this way, i&#39;ll cut next letters to save space. 
...
vocabulary.put(&quot;--..&quot;, &quot;z&quot;);
if(codeToDecode.length()&lt;3){
decode += vocabulary.get(codeToDecode);
}
if(codeToDecode==&quot;...---...&quot;){
decode=&quot;SOS&quot;;
}
for (int i = 0; i &lt;codeToDecode.length(); i++) {
if (codeToDecode.charAt(i) == &#39;/&#39;) { // Here must be the problem. &#39;/&#39; is the blank space. My code &quot;decodes&quot; 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 &quot;||i==codeToDecode.length()&quot; in if statement, but it didn&#39;t work.
decode += vocabulary.get(codeToDecode.substring(flag, i));
flag = i + 1;
} if(codeToDecode.charAt(i)==&#39;/&#39;&amp;&amp;codeToDecode.charAt(i+1)==&#39;/&#39;){
decode+=&quot; &quot;;
i+=2;
flag+=2;
}
}
decode=decode.toUpperCase();
System.out.println(decode);
}
}

I understand there are many problems to come with my approach( I'm sure there is a better way to complete this task) but I'm trying to finish this one on my own without looking at the ready examples. I hope my code is clear as well as my explanations. Thank you in advance.

Peace and Love!

答案1

得分: 2

java是从0开始索引的。你基本知道这一点;你的for循环从0到i &lt; codeToDecode.length()

所以这个:for (int i = 0; i &lt; 10; i++) 会打印出.. 0到9。它永远不会打印10。这就是为什么它有效:一个长度为10的字符串,如果你写:str.charAt(9),它会给出它的最后一个字符。charAt(9)会得到第10个字符(因为.charAt(0)会得到第一个字符)。

所以,如果你写:if (i == codeToDecode.length()),那将__永远不会发生__。在最后一个字符位置,i是9,而codeToDecode.length()是10。尝试使用 if (i == codeToDecode.length() - 1)

注:一些代码风格的建议:

  • codeToDecode相当不方便。也许只用 code 就可以了。
  • 在一个单独的方法中填充那个字典,会更加清晰。
  • 如果不需要的话,不要包含显式的边界情况(比如:如果输入大小小于3),在这里不应该需要。一旦你修复了bug,你的主循环就能完成任务。
  • 注意,SOS的实际摩斯码是无限重复的SOSOSOSOSO...的任何子序列,其中至少包含...---...。例如,.---...---...---...--- 也是一个SOS。如果你想要重复呼叫SOS,你不会发出6个点,只需无限重复3个短划和3个点。这个想法还包括,潜在的营救者最终会在某个未知的点开始在你无限序列中的某个位置捕捉信号。从这个思路来看,就可以理解为什么SOS是这样工作的。
英文:

java is 0-indexed. You sort of know this; your for loop goes from 0 to i &lt; codeToDecode.length().

So this: for (int i = 0; i &lt; 10; i++) will print.. 0 through 9. It never prints 10. This is why it works: A string of length 10 will give up its last character if you write: str.charAt(9). charAt(9) gets you the 10th character (because .charAt(0) gets you the first).

So, if you write: if (i == codeToDecode.length()), that's never going to happen. At the final char position, i is 9, and codeToDecode.length() is 10. Try if (i == codeToDecode.length() - 1).

NB: Some code style tips:

  • codeToDecode is quite unwieldy. Maybe just code is fine.
  • Fill that dictionary in a separate method, so much cleaner.
  • Don't include explicit cornercases (such as: If input size below 3) if not needed, and it shouldn't be needed here. Your main loop will get the job done, once you fix the bug.
  • Note the actual morse code for SOS is any subsequence of an endlessly repeating SOSOSOSOSO.... that contains at least ...---.... For example, .---...---...---...--- is also an SOS. If you want to repeatedly call out an SOS, you don't do 6 dots, just keep repeating 3 dashes and 3 dots forever. The idea is also that a potential rescuer will eventually get in range and starts picking up the signal at some unknown point in your endless sequence. With that mindset it should be obvious why SOS works this way.

huangapple
  • 本文由 发表于 2020年8月23日 18:47:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63546050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定