我不确定如何将我的字符串按 5 计数,然后将莫尔斯电码转换为数字。我使用 for 循环并使用带有似乎不起作用的子字符串 bt 的 if 语句进行炒作。
import acm.program.*;
public class MorseDecoder extends ConsoleProgram
{
public void run()
{
int digit = 0;
String question = readLine("Please enter the morse code: ");
String morse = question.substring(30);
for (int i = 0; i == question.length(); i += 5)
{
if (morse.equals(".----")) {
digit = 1;
}
else if (morse.equals("..---")) {
digit = 2;
System.out.println(digit);
}
else if (morse.equals("...--")) {
digit = 3;
System.out.println(digit);
}
else if (morse.equals("....-")) {
digit = 4;
System.out.println(digit);
}
else if (morse.equals(".....")) {
digit = 5;
System.out.println(digit);
}
else if (morse.equals("-....")) {
digit = 6;
System.out.println(digit);
}
else if (morse.equals("--...")) {
digit = 7;
System.out.println(digit);
}
else if (morse.equals("---..")) {
digit = 8;
System.out.println(digit);
}
else if (morse.equals("----.")) {
digit = 9;
System.out.println(digit);
}
else if (morse.equals("-----")) {
digit = 0;
System.out.println(digit);
}
else {
System.out.println("NaN");
}
}
}
//~ Methods ...............................................................
}
以下是我的 For 循环的编辑:
for (int i = 0; i == question.length(); i += 5)
{
String morse = question.substring(i, i + 5);
if (morse.equals(".----")) {
digit = 1;
System.out.println(digit);
}
else if (morse.equals("..---")) {
digit = 2;
System.out.println(digit);
}
else if (morse.equals("...--")) {
digit = 3;
System.out.println(digit);
}
else if (morse.equals("....-")) {
digit = 4;
System.out.println(digit);
}
else if (morse.equals(".....")) {
digit = 5;
System.out.println(digit);
}
else if (morse.equals("-....")) {
digit = 6;
System.out.println(digit);
}
else if (morse.equals("--...")) {
digit = 7;
System.out.println(digit);
}
else if (morse.equals("---..")) {
digit = 8;
System.out.println(digit);
}
else if (morse.equals("----.")) {
digit = 9;
System.out.println(digit);
}
else if (morse.equals("-----")) {
digit = 0;
System.out.println(digit);
}
else if (morse.length() < 5) {
System.out.println("NaN");
}
}
编辑:我已经更新了我的代码。