这个java代码是将英语转换为莫尔斯电码。
当用户输入标记字符 $ 时,该程序将终止。在输入每个字符串后,程序会显示其等效的摩尔斯电码,在字符之间留一个空格 (ø),在单词之间留两个 øø。
例如。你好世界。输出应为 ....ø.ø.-..ø.-..ø---øø.--ø---ø.-.ø.-..ø-..
我的代码有一些问题。1.当用户输入ø时,我不知道应该在哪里放$来终止程序;2.输出正确但总是以 (ø) 结尾,因为System.out.print(code[variable] + "ø");
这是我的代码:
public class Morse{
public static void main (String [] args)
{
Scanner englishtomorse = new Scanner(System.in);
System.out.println ("Please enter an original sentence in English.");
english = englishtomorse.nextLine();
String str = englishtoMorse(english);
System.out.println(str);
}
public static String englishtoMorse(String english)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String code[] = {"._", "_...", "_._.", "_..",".",".._.","__.", "....",
"..", ".___", "_._", "._..", "__","_ .", "___", ".__.", "__._", "._.",
"...", "_", ".._", "..._", ".__", "_.._", "_.__", "__.."};
english = english.toUpperCase();
for(int xyz = 0; xyz < english.length(); xyz++)
{
char letter = english.charAt(xyz);
if (letter == ' ')
{
System.out.print ("ø");
continue;
}
for(int variable = 0; variable < alphabet.length(); variable++)
{
if(alphabet.charAt(variable) == letter)
{
System.out.print(code[variable] + "ø");
break;
}
}
}
return " ";
}