在莫尔斯电码java上用maven测试时的错误代码



我正在使用Maven测试我的java莫尔斯代码。这是我的提示:

你要用。表示点,-表示短划线。字符的每个莫尔斯电码表示之间必须有一个空格,单词之间必须有三个空格。

我不知道如何在单词之间获得合适的间距,也不知道";SOS";输出读代码行有点困难。

输入"SOS";输出…---。。。输入"CSC 142〃;输出-.-….-…----

这是我的代码:

public class MorseCode {
private static final 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', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',', '.', '?' };
private static final String[] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".---.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----", "--..--", ".-.-.-", "..--.." };
private String InputPhrase;
private static String[] phrase;
private static int wordlength;
public MorseCode(String s, String input) {
// PLACE CODE HERE
InputPhrase = s;
wordlength = input.length();
phrase = new String[wordlength];
stringToMorse(input); 
}
public static String stringToMorse(String input) {
// PLACE CODE HERE
char[] chars = input.toCharArray();
String str = "";
for (int i = 0; i < chars.length; i++) {
for (int index = 0; index < alphabet.length; index++) {
if (alphabet[index] == chars[i]) {
str = str + morse[index] + " ";
}
} 
}
return str; 
}
}

maven码

循环每次迭代时都会添加一个尾随空格。

str = str + morse[index] + " ";

因此,在您处理的最后一封信上,它添加了一个尾随空格,导致SOS测试失败。尝试在方法末尾的代码中放入System.out.println,如:

System.out.println("srt->" + str + "<");

然后你会看到后面的空白。。

至于在单词之间放3个空格,你可以通过在输入中寻找空格来检测工作中断。事实上,你的代码不会在输入中检测到空格,因为空格不在你的字母表数组中。

尝试设置断点并跟踪代码,或者添加System.outs来帮助调试它。

最新更新