您好我正在尝试创建一个将英语翻译为Morse的Java程序,反之亦然。 基本上我无法让所有东西变得兼容..以及如何使用替换所有方法来获取所有输入的变量以替换相应的莫尔斯索引。我并没有试图改变这一点。我真的很努力,想要完成这件事。非常感谢你!
import java.util.Scanner;
public class ProjMorse
{
public static void main( String [] args )
{
Scanner input = new Scanner(System.in);
String [] alpha = {"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"," "};
String [] dottie = {".-", "-...", "-.-.", "-..", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----", "|"};
System.out.println("To convert from English to Morse enter English");
String ans = input.nextLine();
if(ans.equals("English"))
{
System.out.println( "Please enter the text you would like to convert to Morse Code: ");
String English = input.nextLine();
char[] translates = (English.toLowerCase()).toCharArray();
for (int i = 0; i < alpha.length; i++)
{
String s = translates[i].replaceAll('i', (dottie[i]));
}
String s = new String(dottie[i]);
System.out.println(s);
}
else
{
System.out.println( "Please enter the text you would like to convert to English (separate words with '|'):");
String code = input.nextLine();
String[] translates = code.split("[|]", 0);
for (int j = 0; j < dottie.length; j++)
{
alpha[j] = String.valueOf(translates[j]);
}
String s = new String(alpha[j]);
System.out.println(s);
}
}
}
答案 0 :(得分:1)
for (int i = 0; i < alpha.length; i++)
{
String s = translates[i].replaceAll('i', (dottie[i]));
}
这不会起作用,你要做的是逐步翻译要翻译的字符串的每个字符(你已经转换为字符数组)并执行字母'i'的replaceAll
个实例莫尔斯电码字母表中的相对索引。 replaceAll
是String类的一个方法,这不起作用。
如果您尚未将其转换为字符数组,则可以在replaceAll
中包含字符的明文字符串中alpha
对dottie
中的每个项目执行 int characterIndex = 0;
for (char c : alpha)
{
plaintextString.replaceAll(c, dottie[characterIndex]);
characterIndex++;
}
。
String English = input.nextLine();
<强>另外... 强>
首先,如果你问一个问题,它应该包含一个问题,带有问号和所有问题。这样我们才能知道我们在回答什么。如果您有错误,则需要包含错误。您还需要更好地格式化代码,这真的很难阅读...
现在,关于你的代码的注释,不要尝试在一个方法中做所有事情,它是丑陋的,难以阅读和调试。方法应该做一件事(不是多个事情,如获取用户输入,翻译,输出)并做得很好。这背后的原因是,如果您可以在一个屏幕上阅读整个内容,那么可以更好更快地理解方法目的。
此外,变量应以小写字母开头,因此可能会造成混淆: -
{{1}}